选项网址未找到&预检的响应具有无效的HTTP状态代码404

时间:2017-04-03 12:18:29

标签: jquery asp.net-web-api cors

我正在尝试使用jQuery向API方法发送请求。客户端代码如下:

$.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 个答案:

答案 0 :(得分: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();
        }