Posting data to asp.net Web API

2020-06-01 02:46发布

问题:

I'm trying to figure out the new ASP.NET Web API.

So far I've been able to create this method signature and connect to it just fine and get a valid response...

[HttpPost]
public HttpResponseMessage CreateAccount()

I am able to send a request to this method with fiddler and have verified that it is receiving the request.

However, when I try to pass data is when I am running into a problem.

The first thing I tried was...

[HttpPost]
public HttpResponseMessage CreateAccount([FromBody]string email, [FromBody]string password)

And I type

email:xyz,password:abc

into the body of the request in fiddler. When I do this I get a 500 error stating

'Can't bind multiple parameters ('email' and 'password') to the request's content.'

I have also tried this as a method signature...

[HttpPost]
public HttpResponseMessage CreateAccount([FromBody]UserAccountRequestData data)

with the UserAccountRequestData being a simple POCO

public class UserAccountRequestData
{
    public string Email { get; set; }
    public string Password { get; set; }
}

And I put

{Email:xyz,Password:abc}

or

data:{Email:xyz,Password:abc}

into the body of the request. In both cases trying to populate the POCO I am able to reach the method while debugging, but the data object is always null.

I need to understand how to create API methods that accept both strongly typed POCOs and others that accept multiple primitive types like strings and ints.

Thanks

回答1:

You need to set the Content-Type header to application/json and then provide valid JSON.

{"Email":"xyz","Password":"abc"}