27

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?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Aaron
  • 371
  • 1
  • 3
  • 5

7 Answers7

30

if in controller, you can easily get the header by this:

Request.Headers.GetValues("XXX");

if the name does not exist, it will throw an exception.

Sheldon Wei
  • 1,198
  • 16
  • 31
15

You do it the same way, in the controller:

Request.ServerVariables.Get("HTTP_USER_AGENT");

The Request object is part of ASP.NET, MVC or not.

See this for example.

Community
  • 1
  • 1
Oded
  • 489,969
  • 99
  • 883
  • 1,009
6

It should be in the Request.Headers dictionary.

Nick Larsen
  • 18,631
  • 6
  • 67
  • 96
4

.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) {
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
0

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
Robert Dundon
  • 1,081
  • 1
  • 11
  • 22
0

With Core 3.1 and Microsoft.AspNetCore.Mvc.Razor 3.1, you can:

string sid = Request.Headers["SID"];

For whatever header variable you are looking for. Returns NULL if not found.

Ben
  • 433
  • 5
  • 7
0

To be on the safe side in terms of exception throws while the key doesn't exist in the header.

const string HeaderKeyName = "HeaderKey";
bool isValueExist = Request.Headers.TryGetValues(HeaderKeyName, out var values);

if isValueExist true then you should get arrays of values

Mahi
  • 1,019
  • 9
  • 19