簡體   English   中英

ASP.NET內核中響應緩存中間件的使用和好處

[英]The use and benefits of Response Caching Middleware in ASP.NET Core

我想在我的 .NET 核心 API 項目中嘗試緩存機制。

我按照這篇文章配置中間件https://thecodeblogger.com/2021/06/06/middleware-for-response-caching-in-net-core-web-apis/

啟動.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();


        // Response Caching Middleware
        services.AddResponseCaching(options =>
        {
            // Each response cannot be more than 1 KB 
            options.MaximumBodySize = 1024;

            // Case Sensitive Paths 
            // Responses to be returned only if case sensitive paths match
            options.UseCaseSensitivePaths = true;
        });
    }


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        // Response Caching Middleware
        app.UseResponseCaching();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

controller

   [HttpGet]
    [ResponseCache(NoStore = false, Duration = 600, Location = ResponseCacheLocation.Any)]
    public IEnumerable<WeatherForecast> Get()
    {
        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }

我可以在響應中看到這個 header

Cache-Control : public,max-age=600

So I put a break point in the controller, whenever I call the api thorugh postman or browsers it hit the api.

我假設添加 header Cache-Control: public,max-age=600將在客戶端中創建 600 秒的響應緩存,並且不會針對每個請求訪問后端。

如果不是,那么Cache-Control的實際意義是什么

大多數瀏覽器都會在請求 header Cache-Control: max-age=0中覆蓋響應頭的 Cache-Control,從而強制不緩存響應。

對於 Chrome 瀏覽器,要不通過此Cache-Control: max-age=0 header,請打開 Chrome 控制台並輸入

location = "https://your.page.com"

在您的應用程序代碼庫中,您可以將請求 header 設置為 null 以刪除默認的Cache-Control: max-age=0 header。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM