ASP.NET WebApi 跨域请求配置

1.跨域请求如果自定义了客户端请求的Header会先发送一个OPTIONS请求,配置过滤OPTIONS请求

 1  public class OptionsMethodModule:IHttpModule
 2     {
 3         public OptionsMethodModule()
 4         {
 5         }
 6 
 7         public void Dispose()
 8         {
 9         }
10 
11         public void Init(HttpApplication app)
12         {
13             app.BeginRequest += new EventHandler(this.BeginRequest);
14         }
15 
16         public void BeginRequest(object resource,EventArgs e)
17         {
18             HttpApplication app = resource as HttpApplication;
19             HttpContext context = app.Context;
20             if (context.Request.HttpMethod.ToUpper()=="OPTIONS")
21             {
22                 context.Response.StatusCode = 200;
23                 context.Response.End();
24             }
25         }
26     }
新建一个处理类OptionsMethodModule.cs

 然后就是去webconfig里配置处理节点

<system.webServer>
<modules>
<add name="OptionsMethodModule" type="你的命名空间.OptionsMethodModule"/>
</modules>
</system.webServer>

 

2.配置跨域的两个方案

A.Webconfig配置

  <system.webServer>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
      <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Credentials" value="true" />
        <add name="Access-Control-Allow-Methods" value="POST,GET,PUT,PATCH,DELETE,OPTIONS" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,userid,corpid" />
    <!--服务端自定义header-->
                <add name="Access-Control-Expose-Headers" value="errcode,errmsg" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>    

 

B.动态配置

  待续。。。。

posted @ 2019-11-07 13:20  崔国亮  阅读(599)  评论(0)    收藏  举报