Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract custom header value?

I have this exact code from the accepted answer in my project which I need to migrate into ASP.NET Core MVP.

How to extract custom header value in Web API message handler?

var env = Request.Headers.GetValues("environment").First(); 

How can I implement this in .NET Core?

I hope this is not considered to be a duplicate question because I am trying to do this with the new system rather than the old one. I would also be fine if someone adds an answer to the link regarding the current version.

Edit: Where all types for http headers gone in ASP.NET 5? I tried this link but API may have changed. I don't think this is a duplicate for that question either.

like image 636
Kemal Tezer Dilsiz Avatar asked Aug 05 '16 17:08

Kemal Tezer Dilsiz


People also ask

How do I get custom header values in net core API?

Using IHTTPContextAccessor to extract custom header The above–discussed HttpContext or Request class gives us access to metadata including headers of given HttpContext within Controller. However, if you need to access headers or any HttpContext metadata in other services or modules then please use IHTTPContextAccessor.

How do I capture a request header?

You will need to create a Request Attribute for the request headers you want to capture in Settings -> Server-side service monitoring -> Request Attribute. You will have to specify the request attributes you want to capture in the configuration.


2 Answers

Request.Headers returns Microsoft.AspNetCore.Http.IHeaderDictionary interface that define next property:

StringValues this[string key] { get; set; } 

IHeaderDictionary has a different indexer contract than IDictionary, where it will return StringValues.Empty for missing entries.

Return type: Microsoft.Extensions.Primitives.StringValues

Returns: The stored value, or StringValues.Empty if the key is not present.

So, you can simply use Request.Headers["environment"] to get value of "environment" header

like image 51
Set Avatar answered Oct 15 '22 10:10

Set


Since this answer is viewed quite a lot, you can also access this fields by using attributes in the parameters. Here is an example:

enter image description here

In the request you can access any fields in the body, queryString or headers. Here is the Postman example regarding the authorization header:

enter image description here

like image 33
Júlio Almeida Avatar answered Oct 15 '22 10:10

Júlio Almeida