aspnet mvc 中 跨域請求的處理方法

  ASP.NET 處理跨域的兩種方式web

 

     方式1,後端程序處理。原理:給響應頭加上容許的域便可,*表示容許全部的域後端

                定義一個cors的過濾器跨域

 

加在在action或者controller上面便可cors

 

 具體代碼:ide

[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文件便可。spa

 

找到system.WebServer節點下面添加如下便可blog

 

 

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

 
相關文章
相關標籤/搜索