Learn how to access the body, parameters and headers of an incoming HTTP request in a C# controller. Use Request object or attributes to get the data.
In a C# controller, you can use the Request object to access the body, parameters, and headers of an incoming HTTP request. Here is an example of how you can access these values in a controller action:
[HttpPost]
public IActionResult Create([FromBody] string body, [FromQuery] string parameter, [FromHeader] string header)
{
// Access the request body using the "body" parameter
var requestBody = body;
// Access query parameters using the "parameter" parameter
var queryParameter = parameter;
// Access headers using the "header" parameter
var requestHeader = header;
// Your code to handle the request
...
}
In the above example, the “[FromBody]” attribute is used to bind the “body” parameter to the request body, the “[FromQuery]” attribute is used to bind the “parameter” parameter to the query string, and the “[FromHeader]” attribute is used to bind the “header” parameter to the request header.
Alternatively, you can use Request.Form
, Request.Query
and Request.Headers
to get the respective data.
var body = Request.Form["body"];
var parameter = Request.Query["parameter"];
var header = Request.Headers["header"];
Note that this is a simplified example, and in real-world scenarios, the body, parameters, and headers are usually deserialized into objects, and model validation is done before handling the request.