I am making an HTTP POST method to get data. I have an idea to create a method to get a specific arguments but when I don't have idea to get the arguments taken. In HTTP GET, arguments are in the URL and is more easy to get the arguments. How do I create a method to take all the data in HTTP Post? In PHP for example when you show the var $_POST you show all data in the body post. How can I do this in C#?
My method is this:
[HttpPost]
[AllowAnonymous]
public IHttpActionResult Test()
{
// Get URL Args for example is
var args = Request.RequestUri.Query;
// But if the arguments are in the body i don't have idea.
}
Web API has a feature which automatically binds argument posted to an action inside a controller. This is called Parameter Binding. It allows you to simply request the object inside the URL or the body of the POST request, and it does the deserialization magic for you using a thing called Formatters. There is a formatter for XML, JSON, and other known HTTP request types.
For example, lets say I have the following JSON:
{
"SenderName": "David"
"SenderAge": 35
}
I can create an object which matches my request, we'll call it SenderDetails
:
public class SenderDetails
{
public string SenderName { get; set; }
public int SenderAge { get; set; }
}
Now, by receiving this object as a parameter in my POST action, I tell WebAPI to attempt to bind that object for me. If all goes well, I'll have the information available to me without needing to do any parsing:
[Route("api/SenderDetails")]
[HttpPost]
public IHttpActionResult Test(SenderDetails senderDetails)
{
// Here, we will have those details available,
// given that the deserialization succeeded.
Debug.Writeline(senderDetails.SenderName);
}
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