.NET Core 中有等价的 HttpContext.Response.Cache 吗?
生活随笔
收集整理的這篇文章主要介紹了
.NET Core 中有等价的 HttpContext.Response.Cache 吗?
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
咨詢區(qū)
jackmusick:
我想禁掉瀏覽器緩存,這樣我的client端每次都能看到server端的最新內(nèi)容,在 asp.net 時(shí)代可以這么寫。
public?class?NoCacheAttribute?:?ActionFilterAttribute {??public?override?void?OnResultExecuting(ResultExecutingContext?filterContext){filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);filterContext.HttpContext.Response.Cache.SetNoStore();base.OnResultExecuting(filterContext);} }但在 asp.net core 項(xiàng)目中我發(fā)現(xiàn)并沒有 HttpContext.Response.Cache 屬性,請(qǐng)問是否有其他可替換的方式?
回答區(qū)
Darin Dimitrov:
你可以直接在 response header 上添加你需要設(shè)置的值,參考如下代碼:
public?class?NoCacheAttribute?:?ActionFilterAttribute {public?override?void?OnResultExecuting(ResultExecutingContext?filterContext){filterContext.HttpContext.Response.Headers["Cache-Control"]?=?"no-cache,?no-store,?must-revalidate";filterContext.HttpContext.Response.Headers["Expires"]?=?"-1";filterContext.HttpContext.Response.Headers["Pragma"]?=?"no-cache";base.OnResultExecuting(filterContext);} }mk_yo:
在 asp.net core 中,ResponseCache 特性被保留了下面,所以你可以像下面這樣設(shè)置。
[ResponseCache(NoStore?=?true,?Location?=?ResponseCacheLocation.None)]public?class?HomeController?:?Controller{}Marco Alves:
如果你需要在全局作用域上禁用,可以利用 Middleware 機(jī)制實(shí)現(xiàn),參考如下代碼。
namespace?Onsolve.ONE.WebApi.Middlewares {public?sealed?class?RequestHandlerMiddleware{private?readonly?RequestDelegate?next;private?readonly?ILogger?logger;public?RequestHandlerMiddleware(ILogger<RequestHandlerMiddleware>?logger,?RequestDelegate?next){this.next?=?next;this.logger?=?logger;}public?async?Task?Invoke(HttpContext?context){await?next(context);context.Response.Headers["Cache-Control"]?=?"no-cache,?no-store,?must-revalidate";context.Response.Headers["Expires"]?=?"-1";context.Response.Headers["Pragma"]?=?"no-cache";}} }點(diǎn)評(píng)區(qū)
這功能好,讓瀏覽器實(shí)時(shí)查看server端內(nèi)容,尤其是集成到中間件中,學(xué)習(xí)了。
總結(jié)
以上是生活随笔為你收集整理的.NET Core 中有等价的 HttpContext.Response.Cache 吗?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 玩机器学习,能不知道它?
- 下一篇: 设计模式之责任链