开发者

Get header values in ASP.NET MVC

开发者 https://www.devze.com 2023-01-18 22:12 出处:网络
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

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?


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.


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.


It should be in the Request.Headers dictionary.


.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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号