17

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

jdavis
  • 8,255
  • 14
  • 54
  • 62

1 Answers1

17

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

{"Email":"xyz","Password":"abc"}
Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
  • 2
    +1 for Darrel Miller answer. Also you can refer to the answer given for [Sending JSON object to Web API](http://stackoverflow.com/questions/13870161/sending-json-object-to-web-api). It does give you a sample code for your question. – Amit Rai Sharma Mar 11 '13 at 15:16