Owin Self Host WebApi2上的CORS错误

时间:2022-02-05 13:31:33

I have a WebApi2 OWIN SelfHost application and a REST method. I made a JQuery ajax call to the service but I get the error "No 'Access-Control-Allow-Origin'", se below:

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

I have added the Nuget package "Microsoft.Owin.Cors" in order to anable cors.

我已经添加了Nuget软件包“Microsoft.Owin.Cors”以便为可靠的角色添加。

Here is my startup API code:

这是我的启动API代码:

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

My API Controller class:

我的API控制器类:

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

My API Controller method:

我的API控制器方法:

[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)
    };
}

Here is my ajax code:

这是我的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);
    }
});

Error message: "Failed to load resource: the server responded with a status of 405 (Method Not Allowed) url.../api/car/get/6975908 XMLHttpRequest cannot load url.../api/car/get/6975908. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'url...:62456' is therefore not allowed access."

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

I only need to enable CORS at this point, and dont need to Authorize, I have set the [AllowAnonymous] attribute on the controller. What might be the problem?

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

1 个解决方案

#1


3  

I found the problem. The "UseCors" method should be on the app level in the startup class, not the mapped apiApp. See complete statup below.

我发现了问题。 “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);
        });
    }
}

#1


3  

I found the problem. The "UseCors" method should be on the app level in the startup class, not the mapped apiApp. See complete statup below.

我发现了问题。 “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);
        });
    }
}