OPTIONS 405 (Method Not Allowed) web api 2

user1987162 picture user1987162 · Oct 30, 2014 · Viewed 28.4k times · Source

I have created a web api 2 and I'm trying to do a cross domain request to it but I'm getting the following error:

OPTIONS http://www.example.com/api/save 405 (Method Not Allowed)

I have had a look around and most resolutions for this problem are saying that I need to install CORs from NuGet and enable it so I have installed the package and marked my controller with

[EnableCors("*", "*", "*")]

But this still hasn't resolved the problem.

My ApiController only has the following Save method in:

[ResponseType(typeof(int))]
public IHttpActionResult Save(Student student)
{
    if (ModelState.IsValid)
    {
        using (StudentHelper helper = new StudentHelper())
        {
            return Ok(helper.SaveStudent(student));
        }
    }
    else
    {
        return BadRequest(ModelState);
    }
}

This is my js from a different domain:

$.ajax({
    type: "POST",
    crossDomain: true,
    data: JSON.stringify(student),
    crossDomain: true,
    url: 'http://www.example.com/api/save',
    contentType: "application/json",
    success: function (result) {
        console.log(result);
    }
});

Is there something else I need to do to enable this?

Answer

Flavio Franco Jr. picture Flavio Franco Jr. · Jul 20, 2015

Via nuget make the installation of the CORS web API package for your project:

Install-Package Microsoft.AspNet.WebApi.Cors

In WebApiConfig add the following lines:

var cors = new EnableCorsAttribute ("*", "*", "*");
config.EnableCors (cors);