Get header values in ASP.NET MVC

Viewed 47417

I have a requirement to capture the HTTP User Agent header coming in from a device, take the value and remove a 'uuid' This UUID can then be used to direct the device to the correct location to give it the files relevant to the device.

In webforms I was able to get it using

Request.ServerVariables["HTTP_USER_AGENT"]; //inside of Page_Load method

How would I go about this in MVC?

5 Answers

.Net 6 and above, this is how it works:

Request.Headers.TryGetValue("Auth-Token", out StringValues headerValues);
string jsonWebToken = headerValues.FirstOrDefault();

I prefer the new syntax which is more concise:

[HttpGet]
public async Task<IActionResult> GetAuth(FromHeader(Name = "Auth-Token")] string jwt) {

Headers without hypens -'s don't need the Name, they map automagically:

[HttpGet]
public async Task<IActionResult> GetAuth([FromHeader]string host) {

If there is anyone like me, who Googled to see how to get the Content-Type HTTP request header specifically, it's fairly easy:

Request.ContentType
Related