Read request headers as an object in ASP.Net Core

Reading headers is a standard operation in ASP.NET Core and has been around for ages. I even wrote a post summarizing all methods of passing parameters: ASP.NET Core in .NET 5 – pass parameters to actions. ASP.NET Core introduced handy attributes to handle parameters in controller methods, like [FromQuery] or [FromHeader]. But is there a way to use those attributes and read headers as a custom object? Let’s see.

This is how a standard controller method looks like.

In this example [FromBody] means that forecast will be mapped into an object from the request body, and [FromHeader] means that parentRequestId will be taken from the header. That works great, but how to map more headers, preferrable as a separate object?

Let’s take a look at this code:

And ForecastHeaders looks like this:

Have you noticed, that I used [FromHeader] in both controller method parameter declaration and inside my custom class?

Now let’s make a request with Postman.

And result? Are you surprised as I was? 😀

It worked!

All headers were mapped correctly, as a custom object. Notice that Sorting was also mapped, even if it comes from the query parameter, not the header. It proves you can combine those two if that makes sense.

All of it is available in my GitHub – check it out.

I’m not sure if it’s a bug or a feature… but I like it! ❤️

2 thoughts on “Read request headers as an object in ASP.Net Core

  1. This is cool but what about swagger? Have you checked how it renders headers? I’ve been there before it tells you headers are an object instead of headers one for each header field

Leave a Reply

Your email address will not be published. Required fields are marked *