SetValidUntilExpires替代方案

时间:2018-05-24 10:41:06

标签: c# asp.net-core

asp.net核心中context.Response.SetValidUntilExpires(true)的替代方案是什么? 我在asp.net应用中检查了标题,但在将标记设置为truefalse时找不到任何更改。

context.Response.Cache.SetExpires(DateTime.Now.AddDays(7));
context.Response.Cache.SetValidUntilExpires(true);
context.Response.Cache.SetCacheability(HttpCacheability.Public);

1 个答案:

答案 0 :(得分:0)

每当您想要缓存某些内容时,请不要信任该客户端。客户端可以轻松忽略它并一次又一次地询问您的API。 更好的方法是使用服务器端缓存技术。

但是,可以使用 ResponseCacheAttribute 来解决您的问题。这是一个例子。

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        // GET api/values
        [HttpGet]
        [ResponseCache(Duration = 123, VaryByHeader = "User-Agent")]
        public IEnumerable<string> Get()
        {
            return new string[] {"value1", "value2"};
        }

    }
}

如果您要提供静态文件。通过在项目的Startup.cs文件中配置缓存来实现缓存。

以下是一个例子:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;

using Microsoft.Net.Http.Headers; // required

namespace WebApplication1
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            var durationInSeconds = (int) TimeSpan.FromDays(1).TotalSeconds;
            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = context =>
                {
                    context.Context.Response.Headers[HeaderNames.CacheControl] =
                        $"public,max-age={durationInSeconds}";
                }
            });

            app.UseMvc();
        }
    }
}