from:http://www.cnblogs.com/xishuai/p/aspnet-core-cors.htmlcss
CORS 全称"跨域资源共享"(Cross-origin resource sharing)。html
跨域就是不一样域之间进行数据访问,好比 a.sample.com 访问 b.sample.com 中的数据,咱们若是不作任何处理的话,就会出现下面的错误:web
XMLHttpRequest cannot load b.sample.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'a.sample.com' is therefore not allowed access. The response had HTTP status code 404.json
请求和响应信息:api
Response Headers
Content-Type:text/html; charset=utf-8 Server:Microsoft-IIS/10.0 X-Powered-By:ASP.NET Request Headers Accept:*/* Accept-Encoding:gzip, deflate Accept-Language:zh-CN,zh;q=0.8 Connection:keep-alive Content-Length:32384 Host:b.sample.com Origin:a.sample.com
当请求发起后,Host 会获取 Origin,而后进行判断是否赞成这个请求,判断的标准就是 Access-Control-Allow-Origin,若是 Host 服务器指定了 Origin 的配置,那么在响应头就会有:跨域
Access-Control-Allow-Origin:a.sample.com
相关的 Access-Control-*:缓存
- Access-Control-Allow-Origin:指定请求头中 Origin 是否被访问,若是值为 *,则表示可让任何 Origin 访问。
- Access-Control-Request-Method:容许的 HTTP 请求方法,经常使用 Get、Post、Put 等,若是值为 *,则表示容许全部的 HTTP 请求方法访问。
- Access-Control-Expose-Headers:客户端默承认以从服务器获取响应头中的 Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma 字段信息,若是须要额外获取其它 header 字段信息,则须要在服务端进行配置。
Access-Control-Request-Headers:容许客户端向服务器发送的额外请求头信息,和上面的 Access-Control-Expose-Headers 比较类似,但方向是相反的,通常会用在添加自定义 header 的时候,好比 X-Param 等等。 - Access-Control-Allow-Credentials:若是值为 true,则表示服务端能够接受客户端发送的 Cookie 信息,但客户端请求中须要同时设置
withCredentials = true;
。 - Access-Control-Max-Age:请求检查的缓存时间,即在一段时间内,客户端向服务器发送请求,不须要再进行检查 Origin 的配置,而是直接进行请求访问,固然服务器更改配置后除外。
以上是 CORS 的基本相关信息,咱们在 ASP.NET MVC 应用程序开发中,须要手动配置 CORS:服务器
public class AllowCorsAttribute : ActionFilterAttribute { private string[] _domains; public AllowCorsAttribute(params string[] domains) { _domains = domains; } public override void OnActionExecuting(ActionExecutingContext filterContext) { var context = filterContext.RequestContext.HttpContext; if (context.Request.UrlReferrer != null) { var host = context.Request.UrlReferrer?.Host; if (host != null && _domains.Contains(host)) { context.Response.AddHeader("Access-Control-Allow-Origin", $"http://{host}"); } } else { context.Response.AddHeader("Access-Control-Allow-Origin", "*"); } context.Response.AddHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT"); context.Response.AddHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"); base.OnActionExecuting(filterContext); } }
上面代码就是截获每次 Action 请求,手动向请求上下文中增长相应头的配置,以达到 CORS 的目的,Action 配置:微信
[AllowCors("a.sample.com", "c.sample.com")] public ActionResult Index() { return View(); }
而在 ASP.NET WebAPI 项目中配置 CORS,就不须要上面那么复杂了,咱们只须要安装:markdown
Install-Package Microsoft.AspNet.WebApi.Cors
而后配置启用 CORS:
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.EnableCors(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } }
最后在对应的 Action 上面添加 CORS 配置就好了:
[EnableCors(origins: "http://a.sample.com", headers: "*", methods: "get,post", SupportsCredentials = true)] public ActionResult Index() { return View(); }
在 ASP.NET Core 的 CORS 配置和上面差很少,配置方法:
ConfigureServices 中添加配置:
public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); services.AddCors(options => options.AddPolicy("CorsSample", p => p.WithOrigins("http://a.example.com", "http://c.example.com").AllowAnyMethod().AllowAnyHeader())); }
Configure 中启用配置:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.UseCors("CorsSample"); }
Action 启用对应的 CORS,不启用使用[DisableCors]
。
[EnableCors("CorsSample")] public ActionResult Index() { return View(); }
固然 CORS 在 ASP.NET Core 的使用不只于此,你也能够进行自定义,具体查看最后的参考资料。
跨域除了 CORS,还有其它的解决方式:
- JSONP:经过在文档中嵌入一个
<script>
标记来从另外一个域中返回数据,因此只支持 GET 请求,但使用比较简单,资料:ASP.NET Web API 配置 JSONP - document.domain:JS 配置代码
document.domain = ‘sample.com’;
,设置完以后,同域之间就能够 JS 互相访问了,但存在一些隐患,好比一个站点被 JS 注入了,那么就会牵扯到其它站点,资料:ASP.NET 页面禁止被 iframe 框架引用
参考资料: