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节点下面添加以下即可
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="*" /> <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" /> </customHeaders> </httpProtocol>
原文地址:https://www.cnblogs.com/jimsfriend/p/9253266.html
时间: 2024-10-07 19:06:27