Core2中使用Microsoft.AspNetCore.Mvc下的ResponseCacheAttribute特性来控制Http Get请求的缓存

原理是设置http请求 响应头的Cache-control来告诉浏览器如何进行客户端缓存

1、在Startup的ConfigureServices方法里面设置一个CacheProfiles,Duration属性定义浏览器缓存的秒数,CacheProfiles一个通用的缓存配置项

 services.AddMvc(option =>
{
/*客户端缓存*/
option.CacheProfiles.Add("default", new Microsoft.AspNetCore.Mvc.CacheProfile
{
Duration = /*10分钟*/
});
});

2、在需要缓存的Action上面添加ResponseCacheAttribute特性,CacheProfileName 的值使用服务配置的名称,该Action将使用配置项进行缓存

[ResponseCache(CacheProfileName = "default")]

也可以在Action 上赋予 Duration 值,指定浏览器缓存的时间

查看ResponseCacheAttribute中的代码

    public unsafe IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
{
//IL_0000: Unknown result type (might be due to invalid IL)
//IL_0008: Unknown result type (might be due to invalid IL)
//IL_000e: Unknown result type (might be due to invalid IL)
//IL_0025: Unknown result type (might be due to invalid IL)
//IL_0032: Expected Ref, but got Unknown
//IL_0046: Unknown result type (might be due to invalid IL)
if (serviceProvider == (IServiceProvider))
{
throw new ArgumentNullException("serviceProvider");
}
IOptions<MvcOptions> requiredService = serviceProvider.GetRequiredService<IOptions<MvcOptions>>();
CacheProfile cacheProfile = null;
if (this.CacheProfileName != null)
{
((IDictionary)(?)requiredService.Value.CacheProfiles).TryGetValue((!)this.CacheProfileName, ref *(!*)(&cacheProfile));
if (cacheProfile == null)
{
throw new InvalidOperationException(Resources.FormatCacheProfileNotFound(this.CacheProfileName));
}
}
this._duration = (this._duration ?? ((cacheProfile != null) ? cacheProfile.Duration : null));
this._noStore = (this._noStore ?? ((cacheProfile != null) ? cacheProfile.NoStore : null));
this._location = (this._location ?? ((cacheProfile != null) ? cacheProfile.Location : null));
this.VaryByHeader = (this.VaryByHeader ?? ((cacheProfile != null) ? cacheProfile.VaryByHeader : null));
this.VaryByQueryKeys = (this.VaryByQueryKeys ?? ((cacheProfile != null) ? cacheProfile.VaryByQueryKeys : null));
return new ResponseCacheFilter(new CacheProfile
{
Duration = this._duration,
Location = this._location,
NoStore = this._noStore,
VaryByHeader = this.VaryByHeader,
VaryByQueryKeys = this.VaryByQueryKeys
});
}

可以得知Action上设置-----优先级高于--CacheProfiles里面的配置

缓存最终通过ResponseCacheFilter过滤器来实现,ResponseCacheFilter 的代码:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Core;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.ResponseCaching;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq; namespace Microsoft.AspNetCore.Mvc.Internal
{
/// <summary>
/// An <see cref="T:Microsoft.AspNetCore.Mvc.Filters.IActionFilter" /> which sets the appropriate headers related to response caching.
/// </summary>
public class ResponseCacheFilter : IResponseCacheFilter, IActionFilter, IFilterMetadata
{
private readonly CacheProfile _cacheProfile; private int? _cacheDuration; private ResponseCacheLocation? _cacheLocation; private bool? _cacheNoStore; private string _cacheVaryByHeader; private string[] _cacheVaryByQueryKeys; /// <summary>
/// Gets or sets the duration in seconds for which the response is cached.
/// This is a required parameter.
/// This sets "max-age" in "Cache-control" header.
/// </summary>
public int Duration
{
get
{
return (this._cacheDuration ?? this._cacheProfile.Duration) ?? ;
}
set
{
this._cacheDuration = value;
}
} /// <summary>
/// Gets or sets the location where the data from a particular URL must be cached.
/// </summary>
public ResponseCacheLocation Location
{
get
{
return (this._cacheLocation ?? this._cacheProfile.Location) ?? ResponseCacheLocation.Any;
}
set
{
this._cacheLocation = value;
}
} /// <summary>
/// Gets or sets the value which determines whether the data should be stored or not.
/// When set to <see langword="true" />, it sets "Cache-control" header to "no-store".
/// Ignores the "Location" parameter for values other than "None".
/// Ignores the "duration" parameter.
/// </summary>
public bool NoStore
{
get
{
return (this._cacheNoStore ?? this._cacheProfile.NoStore) ?? false;
}
set
{
this._cacheNoStore = value;
}
} /// <summary>
/// Gets or sets the value for the Vary response header.
/// </summary>
public string VaryByHeader
{
get
{
return this._cacheVaryByHeader ?? this._cacheProfile.VaryByHeader;
}
set
{
this._cacheVaryByHeader = value;
}
} /// <summary>
/// Gets or sets the query keys to vary by.
/// </summary>
/// <remarks>
/// <see cref="P:Microsoft.AspNetCore.Mvc.Internal.ResponseCacheFilter.VaryByQueryKeys" /> requires the response cache middleware.
/// </remarks>
public string[] VaryByQueryKeys
{
get
{
return this._cacheVaryByQueryKeys ?? this._cacheProfile.VaryByQueryKeys;
}
set
{
this._cacheVaryByQueryKeys = value;
}
} /// <summary>
/// Creates a new instance of <see cref="T:Microsoft.AspNetCore.Mvc.Internal.ResponseCacheFilter" />
/// </summary>
/// <param name="cacheProfile">The profile which contains the settings for
/// <see cref="T:Microsoft.AspNetCore.Mvc.Internal.ResponseCacheFilter" />.</param>
public ResponseCacheFilter(CacheProfile cacheProfile)
{
this._cacheProfile = cacheProfile;
} /// <inheritdoc />
public void OnActionExecuting(ActionExecutingContext context)
{
//IL_0008: Unknown result type (might be due to invalid IL)
//IL_0051: Unknown result type (might be due to invalid IL)
//IL_00d4: Unknown result type (might be due to invalid IL)
//IL_0185: Unknown result type (might be due to invalid IL)
if (context == null)
{
throw new ArgumentNullException("context");
}
if (!this.IsOverridden(context))
{
if (!this.NoStore && !this._cacheProfile.Duration.get_HasValue() && !this._cacheDuration.get_HasValue())
{
throw new InvalidOperationException(Resources.FormatResponseCache_SpecifyDuration("NoStore", "Duration"));
}
IHeaderDictionary headers = context.HttpContext.Response.Headers;
((IDictionary)(?)headers).Remove((!)"Vary");
((IDictionary)(?)headers).Remove((!)"Cache-Control");
((IDictionary)(?)headers).Remove((!)"Pragma");
if (!string.IsNullOrEmpty(this.VaryByHeader))
{
headers["Vary"] = this.VaryByHeader;
}
if (this.VaryByQueryKeys != null)
{
IResponseCachingFeature responseCachingFeature = context.HttpContext.Features.Get<IResponseCachingFeature>();
if (responseCachingFeature == null)
{
throw new InvalidOperationException(Resources.FormatVaryByQueryKeys_Requires_ResponseCachingMiddleware("VaryByQueryKeys"));
}
responseCachingFeature.VaryByQueryKeys = this.VaryByQueryKeys;
}
if (this.NoStore)
{
headers["Cache-Control"] = "no-store";
if (this.Location == ResponseCacheLocation.None)
{
headers.AppendCommaSeparatedValues("Cache-Control", "no-cache");
headers["Pragma"] = "no-cache";
}
}
else
{
string text = null;
switch (this.Location)
{
case ResponseCacheLocation.Any:
text = "public";
break;
case ResponseCacheLocation.Client:
text = "private";
break;
case ResponseCacheLocation.None:
text = "no-cache";
headers["Pragma"] = "no-cache";
break;
}
text = string.Format((IFormatProvider)CultureInfo.get_InvariantCulture(), "{0}{1}max-age={2}", (object)text, (object)((text != null) ? "," : null), (object)this.Duration);
if (text != null)
{
headers["Cache-Control"] = text;
}
}
}
} /// <inheritdoc />
public void OnActionExecuted(ActionExecutedContext context)
{
} internal bool IsOverridden(ActionExecutingContext context)
{
//IL_0008: Unknown result type (might be due to invalid IL)
if (context == null)
{
throw new ArgumentNullException("context");
}
return Enumerable.Last<IResponseCacheFilter>(Enumerable.OfType<IResponseCacheFilter>((IEnumerable)context.Filters)) != this;
}
}
}

AspNet Core2 浏览器缓存使用的更多相关文章

  1. ASP.NET Boilerplate 学习 AspNet Core2 浏览器缓存使用 c#基础,单线程,跨线程访问和线程带参数 wpf 禁用启用webbroswer右键菜单 EF Core 2.0使用MsSql/MySql实现DB First和Code First ASP.NET Core部署到Windows IIS QRCode.js:使用 JavaScript 生成

    ASP.NET Boilerplate 学习   1.在http://www.aspnetboilerplate.com/Templates 网站下载ABP模版 2.解压后打开解决方案,解决方案目录: ...

  2. aspnet core2中使用csp内容安全策略

    aspnet core2中使用csp内容安全策略 问题:aspnet core2如何使用csp防止xss的攻击 方法: public void ConfigureServices( IServiceC ...

  3. web性能优化:详说浏览器缓存

    TOC 背景 浏览器的总流程图 一步一步说缓存 朴素的静态服务器 设置缓存超时时间 html5 Application Cache Last-Modified/If-Modified-Since Et ...

  4. 理解web缓存 浏览器缓存

    为了: 控制缓存 遇到的现象: 1.开发的时候,浏览器会缓存你的文件,使得你的改动是无效的! 开发过程中:我们是不希望有缓存的. 但正是发布以后,我们是希望页面能够在浏览器缓存,这样用户的体验就会提高 ...

  5. nginx,控浏览器缓存,前端优化方案

    1,困惑 做web项目,对于开发者来说,一个最头痛的问题就是浏览器缓存,有缓存,js更改了,html更改了,发布服务器以后用户往往无法通过浏览器访问到最新的类容,需要用户主动去刷新页面, 因为一直做企 ...

  6. 关于引用JS和CSS刷新浏览器缓存问题

    有时候我们会碰到上线的新版本都要刷新一次缓存的问题.那是因为改了JS的内容,但是JSP引用的地方后面的字符串未发生改变导致浏览器读取浏览器缓存而不会重新加载新的JS内容,以下提供两种解决方式: 1.每 ...

  7. 浏览器缓存相关的Http头介绍:Expires,Cache-Control,Last-Modified,ETag

    转自:http://www.path8.net/tn/archives/2745 缓存对于web开发有重要作用,尤其是大负荷web系统开发中. 缓存分很多种:服务器缓存,第三方缓存,浏览器缓存等.其中 ...

  8. Nginx使用Expires增加浏览器缓存加速

    Max-age是指我们的web中的文件被用户访问(请求)后的存活时间,是个相对的值,相对Request_time(请求时间). Expires它比max-age要麻烦点,Expires指定的时间分&q ...

  9. 浏览器缓存详解:expires,cache-control,last-modified,etag详细说明

    最近在对CDN进行优化,对浏览器缓存深入研究了一下,记录一下,方便后来者 画了一个草图: 每个状态的详细说明如下: 1.Last-Modified 在浏览器第一次请求某一个URL时,服务器端的返回状态 ...

随机推荐

  1. 物体检测,Error: maximum box coordinate value is too large

    使用ssd目标检测,出现error:maximum box coordinate value is larger than 1.100000: ] [1.325] 主要原因在于,用labelImg 标 ...

  2. hdu 6058---Kanade's sum(链表)

    题目链接 Problem Description Give you an array A[1..n]of length n. Let f(l,r,k) be the k-th largest elem ...

  3. firefox设置每次访问时检查缓存

    1.在firefox的地址栏上输入about:config回车2.找到browser.cache.check_doc_frequency选项,双击将3改成1保存即可. 选项每个值都是什么含义的.请看下 ...

  4. SpringBoot之OAuth2.0学习之客户端快速上手

    2.1.@EnableOAuth2Sso 这个注解是为了开启OAuth2.0的sso功能,如果我们配置了WebSecurityConfigurerAdapter,它通过添加身份验证过滤器和身份验证(e ...

  5. Google Optimization Tools实现加工车间任务规划【Python版】

    上一篇介绍了<使用.NET Core与Google Optimization Tools实现加工车间任务规划>,这次将Google官方文档python实现的版本的完整源码献出来,以满足喜爱 ...

  6. Find the Top 10 commands in your linux box!

    history | awk '{print $2;}' | grep -v '^./' | sort -d | uniq -c | sort -nr | head -n 10 grep,  '-v' ...

  7. 【NET CORE微服务一条龙应用】开始篇与目录

    简介 随着业务的发展和变更,项目原先的分布式框架应用业务发展已有些不适应,所以18年初开始准备使用微服务框架,当时正好看到了ocelot项目,特意翻看了源码,发现很灵活和易扩展 于是就开始了微服务的开 ...

  8. 发布webservice之后调用不通

    在websrvice发布文件的webconfig中加入 <httpRuntime maxRequestLength="102400" />  <webServic ...

  9. APiCloud学习

    端API调用 核心模块在 window.api 对象下,默认提供该模块,不需要单独引用. 扩展模块在相应的模块对象下(例如:文件系统模块在fs对象下),需要require引入(var fs = api ...

  10. CentOS7下查看系统环境(内存CPU磁盘使用率)

    1.方法一 yum install atop --安装atop sudo atop--开启监视 2.方法二 top 3.方法三 free --查看没存情况 ps ux --查看CPU 情况 磁盘 df