webapi處理OPTIONS請求

報錯1信息

 Access to XMLHttpRequest at 'http://localhost:4445/api/v/getmsg' from origin 'http://localhost:9528' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.web

解決方案

參考資料:https://segmentfault.com/q/1010000016765176把value值改爲特定的域名。segmentfault

  <system.webServer>   
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="http://localhost:9528" />
    </httpProtocol>    
  </system.webServer>

報錯2信息 

Access to XMLHttpRequest at 'http://localhost:4445/api/v/getmsg' from origin 'http://localhost:9528' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.api

解決方案

增長一行配置文件瀏覽器

<add name="Access-Control-Allow-Credentials" value="true" />

 

報錯3信息

Access to XMLHttpRequest at 'http://localhost:4445/api/v/getmsg' from origin 'http://localhost:9528' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.app

緣由

瀏覽器請求接口時會發送兩個請求,一個是預請求,至關於確認請求,第二個請求才是你要發送的真正的請求,而這個錯誤信息說明的是第一個OPTINOS請求失敗,在服務端沒有處理這個method爲OPTIONS的請求,須要對它處理一下:this

解決方案:

參考資料:關於Web API 2.0中的Options請求返回405的問題spa

                  HTTP Module.net

    public class SpecialMethodModule : IHttpModule
    {
        public SpecialMethodModule()
        {
        }

        public void Init(HttpApplication app)
        {
            app.BeginRequest += new EventHandler(this.BeginRequest);
        }

        public void Dispose()
        {
        }

        public void BeginRequest(object resource, EventArgs e)
        {
            HttpApplication app = resource as HttpApplication;
            HttpContext context = app.Context;
            if (context.Request.HttpMethod.ToUpper() == "OPTIONS")
            {
                context.Response.StatusCode = 200;
                context.Response.End();
            }
        }
    }

在web.config中增長module節點,參考微軟官方文檔,根據IIS版本不一樣,增長的節點方式也不一樣,我是IIS10.0code

<configuration>
  <system.webServer>
    <modules>
      <add name="HelloWorldModule" type="HelloWorldModule"/>
    </modules>
  </system.webServer>
</configuration>

這是我遇到的問題,進行解決以及整理,有其餘問題歡迎溝通。blog

相關文章
相關標籤/搜索