.net core No output cache for admin output cache policy does not work - Stack Overflow

core No output cache for admin output cache policy does not work,if this policy is applied output cache

core No output cache for admin output cache policy does not work, if this policy is applied output cache does not work at all.

Code Example

Cache Policy:

public class AdminNoCachePolicy : IOutputCachePolicy
{
    public ValueTask CacheRequestAsync(OutputCacheContext context, CancellationToken cancellationToken)
    {
        if (context.HttpContext.User.IsInRole("Admin"))
        {
            context.EnableOutputCaching = false;
        }
        else {
            context.EnableOutputCaching = true;
        }

        return ValueTask.CompletedTask;
    }

    public ValueTask ServeFromCacheAsync(OutputCacheContext context, CancellationToken cancellationToken)
    {
        return ValueTask.CompletedTask;
    }

    public ValueTask ServeResponseAsync(OutputCacheContext context, CancellationToken cancellationToken)
    {
        return ValueTask.CompletedTask;
    }
}

I suspect issue with order of service registration tried to change order but did not work. Service Configuration

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddControllersWithViews();

    services.Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new RequireHttpsAttribute());
    });

    services.AddMvc();
    BundleConfig.AddBundles(services);

    services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"], options => options.MigrationsAssembly("My.Web")));

    services.Configure<ApiBehaviorOptions>(options =>
    {
        options.SuppressModelStateInvalidFilter = true;
    });

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(o => o.LoginPath = new PathString("/Account/Login"))
    .AddGoogleOpenIdConnect(options =>
    {
        options.ClientId = Configuration["authentication:google:ClientId"];
        options.ClientSecret = Configuration["authentication:google:ClientSecret"];
    });

    services.AddIdentity<AspNetUsers, ApplicationRole>(options =>
    {
        options.SignIn.RequireConfirmedEmail = true;
        options.User.RequireUniqueEmail = true;
    }).AddEntityFrameworkStores<TvsiContext>().AddDefaultTokenProviders();

    services.ConfigureApplicationCookie(options =>
    {
        options.ExpireTimeSpan = TimeSpan.FromDays(365);
        options.SlidingExpiration = true;
    });   
    

    services.AddSingleton(provider => this.Configuration);

    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    Dapper.SqlMapper.AddTypeMap(typeof(string), System.Data.DbType.AnsiString);

    services.AddMemoryCache();
    services.AddResponseCaching();
    services.AddResponseCompression();
    services.AddRouting();

    services.AddOutputCache(options =>
    {
        options.SizeLimit = 10485760000; // 10GB
        options.AddPolicy("AdminNoCache", new AdminNoCachePolicy());
    });
}

Please advise how to resolve this issue? My doubts are toward service registration order. Thanks

core No output cache for admin output cache policy does not work, if this policy is applied output cache does not work at all.

Code Example

Cache Policy:

public class AdminNoCachePolicy : IOutputCachePolicy
{
    public ValueTask CacheRequestAsync(OutputCacheContext context, CancellationToken cancellationToken)
    {
        if (context.HttpContext.User.IsInRole("Admin"))
        {
            context.EnableOutputCaching = false;
        }
        else {
            context.EnableOutputCaching = true;
        }

        return ValueTask.CompletedTask;
    }

    public ValueTask ServeFromCacheAsync(OutputCacheContext context, CancellationToken cancellationToken)
    {
        return ValueTask.CompletedTask;
    }

    public ValueTask ServeResponseAsync(OutputCacheContext context, CancellationToken cancellationToken)
    {
        return ValueTask.CompletedTask;
    }
}

I suspect issue with order of service registration tried to change order but did not work. Service Configuration

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddControllersWithViews();

    services.Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new RequireHttpsAttribute());
    });

    services.AddMvc();
    BundleConfig.AddBundles(services);

    services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"], options => options.MigrationsAssembly("My.Web")));

    services.Configure<ApiBehaviorOptions>(options =>
    {
        options.SuppressModelStateInvalidFilter = true;
    });

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(o => o.LoginPath = new PathString("/Account/Login"))
    .AddGoogleOpenIdConnect(options =>
    {
        options.ClientId = Configuration["authentication:google:ClientId"];
        options.ClientSecret = Configuration["authentication:google:ClientSecret"];
    });

    services.AddIdentity<AspNetUsers, ApplicationRole>(options =>
    {
        options.SignIn.RequireConfirmedEmail = true;
        options.User.RequireUniqueEmail = true;
    }).AddEntityFrameworkStores<TvsiContext>().AddDefaultTokenProviders();

    services.ConfigureApplicationCookie(options =>
    {
        options.ExpireTimeSpan = TimeSpan.FromDays(365);
        options.SlidingExpiration = true;
    });   
    

    services.AddSingleton(provider => this.Configuration);

    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    Dapper.SqlMapper.AddTypeMap(typeof(string), System.Data.DbType.AnsiString);

    services.AddMemoryCache();
    services.AddResponseCaching();
    services.AddResponseCompression();
    services.AddRouting();

    services.AddOutputCache(options =>
    {
        options.SizeLimit = 10485760000; // 10GB
        options.AddPolicy("AdminNoCache", new AdminNoCachePolicy());
    });
}

Please advise how to resolve this issue? My doubts are toward service registration order. Thanks

Share Improve this question asked Mar 24 at 7:42 bhaktipbhaktip 353 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Your AdminNoCachePolicy does not look right, you can inspect how OutputCacheMiddleware is executed here:

  • https://source.dot/#Microsoft.AspNetCore.OutputCaching/OutputCacheMiddleware.cs,36bbedec3dbc3944,references

Also look at how the default implementation looks like, after that copy paste it and make changes so that it reflects your logic.

  • https://source.dot/#Microsoft.AspNetCore.OutputCaching/Policies/DefaultPolicy.cs,2da295f8d4e197eb,references

Specifically, notice the lack of the following block in your policy:

context.AllowCacheLookup = attemptOutputCaching;
context.AllowCacheStorage = attemptOutputCaching;
context.AllowLocking = true;
 
// Vary by any query by default
context.CacheVaryByRules.QueryKeys = "*";

See how AllowCacheLookup and AllowCacheStorage is used in the middleware.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744255836a4565395.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信