【问题标题】:Net Core Custom Response CacheNet Core 自定义响应缓存
【发布时间】:2021-11-16 18:01:41
【问题描述】:

我需要根据查询字符串中的布尔值来决定是否缓存响应。不幸的是,我找不到这样的例子。你能帮帮我吗?

【问题讨论】:

    标签: asp.net-core caching asp.net-core-mvc responsecache


    【解决方案1】:

    您可以为该场景创建一个自定义中间件,该中间件从查询中读取布尔值并根据该值缓存响应(无论可能是什么)。

    您可以阅读自定义中间件here

    您的中间件应如下所示:

     public class OptionalCachingMiddleware
        {
            private readonly RequestDelegate _next;
            private readonly IServiceProvider _services;
    
            public OptionalCachingMiddleware(RequestDelegate next, IServiceProvider services)
            {
                _next = next;
                _services= services;
            }
    
            public async Task InvokeAsync(HttpContext context)
            {
                var shouldCache = bool.Parse(context.Request.Query["your-query-parameter-name"]);
                if (shouldCache)
                {
                    var responseCache = _services.GetRequiredService<IResponseCache>();
                    // put your caching logic here
                }
    
                // Call the next delegate/middleware in the pipeline
                await _next(context);
            }
        }
    

    【讨论】:

    • 那么这里如何使用响应缓存呢?内存缓存还可以,但是我想不出响应缓存的想法。
    • 您可以将 IResponseCache 服务注入您的中间件并使用它。
    • 谢谢我会调查
    猜你喜欢
    • 1970-01-01
    • 2017-11-23
    • 2019-12-22
    • 2022-06-23
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    相关资源
    最近更新 更多