28

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?

0

7 Answers 7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

what type of exception?
@Zapnologica InvalidOperationException
For .Net Core 6, use TryGetValue instead.
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.

Comments

6

It should be in the Request.Headers dictionary.

Comments

6

.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) {

Comments

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

Comments

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.

Comments

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

1 Comment

note: this answer is for ASP.NET Core.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.