1. 程式人生 > >aspnet mvc 中 跨域請求的處理方法

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

token onf head ken 跨域 AD 技術分享 protoc get

  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>

 

  

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