I need to add many custom headers in my request. I can use something like this
public ActionResult Get([FromHeader, Required]string header1, [FromHeader]string header2, ... , [FromHeader]string headerx)
{
...
...
}
I am not sure if it is good to use that number of parameters in one method. I would like to use something like this
public class HeaderParameters
{
[Required]
public string Header1 { get; set; }
public string Header2 { get; set; }
...
public string Headerx { get; set; }
}
public ActionResult Get([FromHeader]HeaderParameters headerParameters)
{
...
...
}
But it doesn't work.
If I use [FromHeader] attribute for each property of HeaderParameters class Swagger is acting weird.
Request example http://prntscr.com/p14kd7
{
"errors": {
"Device": [
"The Header1 field is required."
]
},
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "0HLPG9SNNJ1U2:00000001"
}
There is an easier way in ASP.NET Core in .Net Core 3.1. Just put [FromHeader]
everywhere, like this:
[HttpPost("multipleHeaders")]
public IActionResult Post([FromHeader] ForecastHeaders forecastHeaders)
{
try
{
Console.WriteLine($"Got a forecast for city: {forecastHeaders.City}," +
$"temperature: {forecastHeaders.TemperatureC} and" +
$"description: {forecastHeaders.Description}!");
}
catch (Exception e)
{
Console.WriteLine(e);
return StatusCode(StatusCodes.Status500InternalServerError);
}
return new AcceptedResult();
}
And ForecastHeaders
look like this:
public class ForecastHeaders
{
[FromHeader]
public string City { get; set; }
[FromHeader]
public int TemperatureC { get; set; }
[FromHeader]
public string Description { get; set; }
[FromQuery]
public string Sorting { get; set; }
}
And when you send a request with Postman:
It works like a charm:
Just put [FromHeader]
everywhere. Work with [FromQuery]
as well.
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