欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

webapi处理OPTIONS请求

程序员文章站 2022-03-06 21:16:04
报错1信息 Access to XMLHttpRequest at 'http://localhost:4445/api/v/getmsg' from origin 'http://localhost:9528' has been blocked by CORS policy: Response t ......

报错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.

解决方案

参考资料:,把value值改成特定的域名。

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

解决方案

增加一行配置文件

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

原因

浏览器请求接口时会发送两个请求,一个是预请求,相当于确认请求,第二个请求才是你要发送的真正的请求,而这个错误信息说明的是第一个optinos请求失败,在服务端没有处理这个method为options的请求,需要对它处理一下:

解决方案:

参考资料:关于web api 2.0中的options请求返回405的问题

                  http module

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

<configuration>
  <system.webserver>
    <modules>
      <add name="helloworldmodule" type="helloworldmodule"/>
    </modules>
  </system.webserver>
</configuration>

这是我遇到的问题,进行解决以及整理,有其他问题欢迎沟通。