Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting data to asp.net Web API

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

like image 670
jdavis Avatar asked Mar 11 '13 14:03

jdavis


People also ask

How do I post data on Web API?

Create a Resource (HTTP POST) In this method set base address of Asp.Net Web API and sets the accept header to application/json that tells the server to send data in JSON Format. PostAsJsonAsyn:This method serializes object into JSON format and send POST request to. After that this method return Response object.

How can we call post method in Web API from URL?

Under the value, we can pass our response data in whichever format we want to return the data. I want to call Post method. Hence, select POST method from the list of HTTP methods. We try and pass the Web API URL in the URL tab in order to make sure you need to first run your project and pass localhost URL.

What is the difference between under posting and over posting in asp net web API?

What is “Under-Posting” and “Over-Posting” in Web API? Ans: “Under-Posting” - When client leaves out some of the properties while binding then it's called under – posting. “Over-Posting” – If the client sends more data than expected in binding then it's called over-posting.


1 Answers

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

{"Email":"xyz","Password":"abc"}
like image 136
Darrel Miller Avatar answered Sep 19 '22 15:09

Darrel Miller