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
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.
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 “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.
You need to set the Content-Type
header to application/json
and then provide valid JSON.
{"Email":"xyz","Password":"abc"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With