【问题标题】:How to set VaryByQueryKeys = new[] { "*" } in startup.cs as globally?如何在 startup.cs 中将 VaryByQueryKeys = new[] { "*" } 设置为全局?
【发布时间】:2021-10-18 13:38:44
【问题描述】:

我使用 .net core 5 并且需要帮助,我想在 startup.cs 中为全局所有请求设置 VaryByQueryKeys = new[] { "*" }。我该怎么做。我知道它可以通过这样的控制器属性来完成.. Screen1

但我需要在 startup.cs Screen2

【问题讨论】:

    标签: .net asp.net-core


    【解决方案1】:

    我使用 .net core 5 并且需要帮助,我想在 startup.cs 中为全局所有请求设置 VaryByQueryKeys = new[] { "*" }。

    您可以在 Configure 方法中自定义一个中间件,如下所示:

    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthentication();
    app.UseAuthorization();
    
    app.UseResponseCaching();
    app.Use(async (context, next) =>
    {
        context.Response.GetTypedHeaders().CacheControl =
            new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
            {
                Public = true,
                MaxAge = TimeSpan.FromSeconds(10)
            };
        var responseCachingFeature = context.Features.Get<IResponseCachingFeature>();
        if (responseCachingFeature != null)
        {
            responseCachingFeature.VaryByQueryKeys = new[] { "QueryKeyName" };
        }
    
        await next();
    });
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 2011-02-11
      • 2017-12-06
      相关资源
      最近更新 更多