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
498 views
in Technique[技术] by (71.8m points)

asp.net web api - WebAPI - Attribute Routing POST not working with WebAPI Cors?

I have the following controller which should accept username and password as payload in a POST. If I change it to HttpGet it works.

[RoutePrefix("api")]
public class AccountController : ApiController
{
    [HttpPost("login/{username}/{password}")]
    [AcceptVerbs("POST")]
    public Login Login(string username, string password)
    {
        Login login = new Login();
        if (username == "user" && password == "pw") login.Success = true;
        else login.Success = false;
        return login;
    }
}

The OPTIONS request can pass through but POST fails.

enter image description here

OPTIONS header:

enter image description here

OPTIONS response:

enter image description here

POST header:

enter image description here

POST response:

enter image description here

Any idea what I'm doing wrong?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You have defined your route with [HttpPost("login/{username}/{password}")] but you don't send the usename and password in the url but in the request body so your route doesn't match so you get the 404.

So you need to change your route to [HttpPost("login")]

In itself it won't work because with Web.API you cannot have multiple action arguments coming from the request body so you need a complex type:

public class LoginInfo {
    public string username { get; set; }
    public string password { get; set; }
}

So for fixed action should look like this:

[HttpPost("login")]
[AcceptVerbs("POST")]
public Login Login(LoginInfo loginInfo)
{
    Login login = new Login();

    if (loginInfo.username == "user" && loginInfo.password == "pw") {
        login.Success = true;
    } else {
        login.Success = false;
    }

    return login;
}

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

...