2017-04-03 85 views
0

我正尝试使用jQuery向API方法发送请求。客户端代码如下:找不到选项网址&对预检的响应具有无效的HTTP状态码404

$.ajax({ 
     type: 'POST', 
     url: endpointLocation, 
     headers: { 
      AuthToken: "myTokenValue",    
      UserId: "12345" 
     }, 
     timeout: 5000, 
     dataType: 'json', 
     data: { 
     isActive: true, 
     empId: 2050 
     }, 
     success: function (result) { 
      debugger; 
     }, 
     error: function (xhr, textStatus, errorThrown) { 
      debugger; 
     } 
    }); 

的Web.config条目:

<handlers> 
     <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> 
     <remove name="OPTIONSVerbHandler" /> 
     <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-Headers" value="Content-Type" /> 
     <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" /> 
     </customHeaders> 
    </httpProtocol> 

我得到一个错误“的XMLHttpRequest无法加载http://domain/application/method/预检响应具有无效的HTTP状态代码404。”在此之后,控制跳转到错误方法。

另外,如果我添加我在web.config文件中发送的头文件,它仍然没有区别。这是我想在web.config中添加页眉:

<add name="Access-Control-Allow-Headers" value="Content-Type, AuthToken, UserId" /> 

我需要因为API端点实现自定义的认证,从头部取值,并验证用户发送这些头。这是无法避免的。

有人可以帮我纠正这个问题吗?

回答

1

尝试添加在Global.asax.cs中以下文件

protected void Application_BeginRequest() 
     { 
      if (Context.Request.HttpMethod != "OPTIONS") return; 
      Context.Response.AddHeader("Access-Control-Allow-Origin", Context.Request.Headers["Origin"]); 
      Context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,x-access-token"); 
      Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); 
      Context.Response.AddHeader("Access-Control-Allow-Credentials", "true"); 
      Context.Response.End(); 
     } 
+0

就不得不添加的authToken与用户ID访问控制允许-header和注释掉Context.Response.AddHeader(“访问 - 控制 - Allow-Origin“,Context.Request.Headers [”Origin“])。 “*”已经在web.config中。 – User2682

相关问题