aspnet mvc 中 跨域请求的处理方法
ASP.NET 处理跨域的两种方式
方式1,后端程序处理。原理:给响应头加上允许的域即可,*表示允许所有的域
定义一个cors的过滤器
加在在action或者controller上面即可
具体代码:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.All, Inherited = true, AllowMultiple = true)] public class CorsAttribute : ActionFilterAttribute, IActionFilter { public override void OnResultExecuted(ResultExecutedContext filterContext) { try { base.OnResultExecuted(filterContext); HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Origin", "*"); HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Headers", "x-requested-with,content-type,requesttype,Token"); HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Methods", "POST,GET"); } catch (Exception exception) { } } }
方式2(IIS处理):(推荐)最简单的处理方式, 原理和上面相同,只不过是由IIS来实现,操作也很简单。修改web.config文件即可。
找到system.WebServer节点下面添加以下即可
具体代码:
1 <httpProtocol> 2 <customHeaders> 3 <add name="Access-Control-Allow-Origin" value="*" /> 4 <add name="Access-Control-Allow-Headers" value="*" /> 5 <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" /> 6 </customHeaders> 7 </httpProtocol>