Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
505 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...