CORS解决WebApi跨域问题(转)
Posted Blogger
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CORS解决WebApi跨域问题(转)相关的知识,希望对你有一定的参考价值。
CORS全称Cross-Origin Resource Sharing,中文全称跨域资源共享。它解决跨域问题的原理是通过向http的请求报文和响应报文里面加入相应的标识告诉浏览器它能访问哪些域名的请求
在WebApiCORS项目上面使用Nuget搜索“microsoft.aspnet.webapi.cors”
然后在App_Start文件夹下面的WebApiConfig.cs文件夹配置跨域
public static class WebApiConfig { public static void Register(HttpConfiguration config) { //跨域配置 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); } }
调用处指定 jQuery.support.cors = true; 这一句就能解决IE8、9对CORS的支持问题
,这种*号是不安全的。因为它表示只要别人知道了你的请求url,任何请求都可以访问到你的资源。这是相当危险的。所以需要我们做一些配置,限制访问权限。比如我们比较常见的做法如下:
配置方法一:
到web.config配置文件中
<add key="cors_allowOrigins" value="*"/> <add key="cors_allowHeaders" value="*"/> <add key="cors_allowMethods" value="*"/>
var allowOrigins = ConfigurationManager.AppSettings["cors_allowOrigins"]; var allowHeaders = ConfigurationManager.AppSettings["cors_allowHeaders"]; var allowMethods = ConfigurationManager.AppSettings["cors_allowMethods"]; var globalCors = new EnableCorsAttribute(allowOrigins, allowHeaders, allowMethods); config.EnableCors(globalCors);
配置方法二:
[EnableCors(origins: "http://localhost:8081/", headers: "*", methods: "GET,POST,PUT,DELETE")] public class ChargingController : ApiController { /// <summary> /// 得到所有数据 /// </summary> /// <returns>返回数据</returns> [HttpGet] public string GetAllChargingData() { return "Success"; } }
参考:http://www.cnblogs.com/landeanfen/p/5177176.html
http://www.cnblogs.com/shy1766IT/p/5215311.html
.net framework4.0通过方法实现
public class CrosHandler : DelegatingHandler { private const string _origin = "Origin"; private const string _accessControlRequestMethod = "Access-Control-Request-Method"; private const string _accessControlRequestHeaders = "Access-Control-Request-Headers"; private const string _accessControlAllowOrigin = "Access-Control-Allow-Origin"; private const string _accessControlAllowMethods = "Access-Control-Allow-Methods"; private const string _accessControlAllowHeaders = "Access-Control-Allow-Headers"; protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { bool isCrosRequest = request.Headers.Contains(_origin); bool isPreflightRequest = request.Method == HttpMethod.Options; if (isCrosRequest) { Task<HttpResponseMessage> taskResult = null; if (isPreflightRequest) { taskResult = Task.Factory.StartNew<HttpResponseMessage>(() => { HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.OK); response.Headers.Add(_accessControlAllowOrigin, request.Headers.GetValues(_origin).FirstOrDefault()); string method = request.Headers.GetValues(_accessControlRequestMethod).FirstOrDefault(); if (method != null) { response.Headers.Add(_accessControlAllowMethods, method); } string headers = string.Join(", ", request.Headers.GetValues(_accessControlRequestHeaders)); if (!string.IsNullOrEmpty(headers)) { response.Headers.Add(_accessControlAllowHeaders, headers); } return response; }, cancellationToken); } else { taskResult = base.SendAsync(request, cancellationToken) .ContinueWith<HttpResponseMessage>(t => { var response = t.Result; response.Headers.Add(_accessControlAllowOrigin, request.Headers.GetValues(_origin).FirstOrDefault()); return response; }); } return taskResult; //return base.SendAsync(request, cancellationToken); } else { return base.SendAsync(request, cancellationToken); } } }
protected void Application_Start() { IOCConfig.RegisterAll(); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); GlobalConfiguration.Configuration.MessageHandlers.Add(new CrosHandler()); }
原文:http://www.cnblogs.com/niuww/p/5569504.html
以上是关于CORS解决WebApi跨域问题(转)的主要内容,如果未能解决你的问题,请参考以下文章