最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin6浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论