【问题标题】:OPTIONS URL not found & Response for preflight has invalid HTTP status code 404OPTIONS URL 未找到 & 预检响应具有无效的 HTTP 状态代码 404
【发布时间】:2017-08-28 07:27:46
【问题描述】:

我正在尝试使用 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 cannot load http://domain/application/method/. Response for preflight has invalid HTTP status code 404”之后控件跳转到错误方法。

另外,如果我在 web.config 文件中添加我发送的标头,它仍然没有区别。这就是我尝试在 web.config 中添加标头的方式:

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

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

有人可以帮我解决这个问题吗?

【问题讨论】:

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


    【解决方案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();
            }
    

    【讨论】:

    • 只需将 AuthToken 和 UserId 添加到 Access-Control-Allow-Headers 并注释掉 Context.Response.AddHeader("Access-Control-Allow-Origin", Context.Request.Headers["Origin "])。 “*”已经在 web.config 中。
    猜你喜欢
    • 2017-09-26
    • 2018-04-25
    • 2016-01-22
    • 2016-04-10
    • 2017-12-22
    • 1970-01-01
    • 2018-03-12
    • 2016-02-13
    • 2016-01-18
    相关资源
    最近更新 更多