Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS error on Owin Self Host WebApi2

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:

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

Here is my startup API code:

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

My API Controller class:

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

My API Controller method:

[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({
    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."

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?

like image 888
Claes-Philip Staiger Avatar asked Dec 01 '25 02:12

Claes-Philip Staiger


1 Answers

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.

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);
        });
    }
}
like image 174
Claes-Philip Staiger Avatar answered Dec 07 '25 16:12

Claes-Philip Staiger