xlfm22 发表于 2017-12-27 21:53:29

IIS ajax CORS 访问发送自定义Header时分析

  场景:
  a站:http://127.0.0.1/a
  b站:http://localhost/b (IIS7.5)
  a站用ajax访问b的资源,代码如下:
  $.ajaxSetup({ xhrFields: { withCredentials: true } });//带cookie,不是重点
  $.ajax({
  url:"http://localhost/b/home/index",
  header:{myheader:"hello"},//自定义头将让浏览器把此次访问当做复杂请求,会先用OPTIONS做 预请求(preflight request)
  success:function(data){
  alert(data);
  }
  });
  b站后台:
  (1)必须要设置的响应头:
  protected void Application_BeginRequest(object sender, EventArgs e)
  {
  var response = this.Context.Response;
  response.Headers["Access-Control-Allow-Origin"] = "http://127.0.0.1";
  response.Headers["Access-Control-Allow-Credentials"] = "true";
  response.Headers["Access-Control-Allow-Methods"] = "POST,GET,PUT,OPTIONS";
  response.Headers["Access-Control-Allow-Headers"] = "myheader";
  }
  如果一切正常,应该正常调用 alert(data);
  但,对,确实没有调用,响应头 Access-Control-Allow-Origin 没有返回给浏览器,预请求没有通过。
  (2)webconfig中:
  <system.webServer>
  <validation validateIntegratedModeConfiguration="false" />
  <handlers>
  <remove name="OPTIONSVerbHandler" />
  <!--<remove name="OPTIONS" /> iis 8 -->
  <add name="OPTIONSVerbHandler" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
  把(2)加上,一切正常了,alert(data)被调用。
  于是,怀疑OPTIONSVerbHandler这个处理器有bug。
https://images2015.cnblogs.com/blog/32687/201706/32687-20170609125102262-1810360354.png
  但始终没找到代码。
  这个ProtocolSupportModule在Protsup.dll中,不是c#的,估计是c++的,不知用什么反射。
页: [1]
查看完整版本: IIS ajax CORS 访问发送自定义Header时分析