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

相关文章
相关标签/搜索