gpt4 book ai didi

ajax - Owin Self Host WebApi2 上的 CORS 错误

转载 作者:行者123 更新时间:2023-12-04 17:41:13 25 4
gpt4 key购买 nike

我有一个 WebApi2 OWIN SelfHost 应用程序和一个 REST 方法。我对该服务进行了 JQuery ajax 调用,但出现错误“No 'Access-Control-Allow-Origin'”,如下所示:

我添加了 Nuget 包“Microsoft.Owin.Cors”以启用 cors。

这是我的启动 API 代码:

app.Map("/api", apiApp =>
{
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
apiApp.UseWebApi(config);
apiApp.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
});

我的 API Controller 类:

[RoutePrefix("car")]
[AllowAnonymous]
public class CarController : ApiController

我的 API Controller 方法:

[HttpGet]
[Route("get/{id}")]
public HttpResponseMessage Get(string id)
{
var car = GetCars().Where(c => c.Id.Equals(id)).FirstOrDefault();
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent<object>(new
{
car
}, Configuration.Formatters.JsonFormatter)
};
}

这是我的 ajax 代码:

$.ajax({
type: "GET",
url: 'url.../api/car/get/6975908',
headers: {
'Access-Control-Allow-Origin': '*',
"X-Requested-With": "XMLHttpRequest"
},
crossDomain: true,
dataType: 'json',
success: function (data) {
if (data.Success) {
alert(data.Content); //display success
}
else {
alert(data.Message) //display exception
}

},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});

错误信息:“无法加载资源:服务器响应状态为 405(方法不允许)url .../api/car/get/6975908XMLHttpRequest 无法加载 url.../api/car/get/6975908。请求的资源上不存在“Access-Control-Allow-Origin” header 。因此不允许访问来源 'url...:62456'。”

此时我只需要启用 CORS,不需要授权,我已经在 Controller 上设置了 [AllowAnonymous] 属性。可能是什么问题?

最佳答案

我发现了问题。 “UseCors”方法应该在启动类中的应用程序级别,而不是映射的 apiApp。请参阅下面的完整设置。

public class Startup
{
public void Configuration(IAppBuilder app)
{
//use cors on server level
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

app.Map("/api", apiApp =>
{
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
apiApp.UseWebApi(config);
});
}
}

关于ajax - Owin Self Host WebApi2 上的 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24379886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com