Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

c# - OPTIONS 405 (Method Not Allowed) web api 2

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...