webapi配置跨域訪問

一、使用System.Web.Http.Cors配置跨域訪問:

1、在App_Start/WebApiConfig.Register方法中進行配置

            //Web API 配置和服務
            //跨域配置
            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));//全部不限制

            參數說明:

            origins:允許訪問的域名,多個域名以逗號分隔。使用“*”全部允許。

            headers:配置所支持的資源,使用“*”全部允許,使用null或“”不允許。

            methods:配置支持的請求方法,使用“*”全部允許,使用null或“”不允許。

            config.EnableCors(new EnableCorsAttribute("http://localhost:1234/,http://localhost:2345/", "*", "*"));//限制域名

 

2、在Web.config中進行配置

           <system.webServer>

                     <httpProtocol>

                           <customHeaders>

                                       <add name="Access-Control-Allow-Origin" value="*" />

                                       <add name="Access-Control-Allow-Methods" value="HEAD, GET, POST, PUT, PATCH, DELETE,                                                  OPTIONS" />

                                       <add name="Access-Control-Allow-Headers" value="*" />

                          </customHeaders>

                   </httpProtocol>

        </system.webServer>

3、自定義類並繼承ActionFilterAttribute類

       

 public class CustomActionFilterAttribute : ActionFilterAttribute
 {
        /// <summary>
        /// 方法執行後
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        public override void OnActionExecuted(HttpActionExecutedContext 
          actionExecutedContext)
        {
            //修改下response
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            base.OnActionExecuted(actionExecutedContext);
        }
    }

 }

將該類對允許跨域的Controller進行配置:

     

    [CustomActionFilterAttribute]
    public class ValuesController : ApiController
    {
     
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

       
        public string Get(int id)
        {
            return "value Get";
        }
    }

當然, EnableCorsAttribute也可以對控制器或接口進行跨域配置。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章