Jquery 找不到选项URL&飞行前响应的HTTP状态代码404无效
我正在尝试使用jQuery向API方法发送请求。客户端代码如下:Jquery 找不到选项URL&飞行前响应的HTTP状态代码404无效,jquery,asp.net-web-api,cors,Jquery,Asp.net Web Api,Cors,我正在尝试使用jQuery向API方法发送请求。客户端代码如下: $.ajax({ type: 'POST', url: endpointLocation, headers: { AuthToken: "myTokenValue", UserId: "12345" }, timeout: 5000, dataType: 'json
$.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状态代码404。在此之后,控件跳转到错误方法
此外,如果我在web.config文件中添加发送的标题,仍然没有什么区别。以下是我尝试在web.config中添加标题的方式:
<add name="Access-Control-Allow-Headers" value="Content-Type, AuthToken, UserId" />
我需要发送这些头,因为API端点实现了从头中获取值并验证用户的自定义身份验证。这是不可避免的
有人能帮我纠正这个问题吗?尝试在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以访问控制允许标头并注释掉Context.Response.AddHeaderAccess-Control-Allow-Origin,Context.Request.Headers[Origin].*已在web.config中。