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)
      {
      }
  }

}

  

扫描二维码关注公众号,回复: 1833044 查看本文章

 方式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>

 

  

猜你喜欢

转载自www.cnblogs.com/jimsfriend/p/9253266.html