Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use [FromHeader] attribute with custom model binding in Asp.Net Core 2.2

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"
}
like image 330
Ivan Berezhnyk Avatar asked Sep 03 '19 09:09

Ivan Berezhnyk


1 Answers

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: enter image description here

It works like a charm: enter image description here

Just put [FromHeader] everywhere. Work with [FromQuery] as well.

like image 198
Mik Avatar answered Sep 19 '22 08:09

Mik