Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get the user-agent from request in asp.net web api self host

I'm trying to get the user-agent in a web api self host and I'm either doing it wrong, or the web api itself is altering the user agent string.

I've tried using several methods to the get the string and they all return the same results, instead of the excepted "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.28 Safari/537.31", I only get "Mozilla/5.0".

I've tried:

var header = request.Headers.SingleOrDefault(h => h.Key == "User-Agent").Value.First();  var header = request.Headers.UserAgent.SingleOrDefault().Product.ToString();  var header = request.Headers.GetValues("User-Agent").FirstOrDefault(); 

Am I doing this wrong, it's self host so I don't have a context to work with.

like image 423
casualtek Avatar asked Mar 09 '13 09:03

casualtek


People also ask

What is User Agent in HTTP request?

The User-Agent request header is a characteristic string that lets servers and network peers identify the application, operating system, vendor, and/or version of the requesting user agent.

How do I enable CORS in Web API?

You can enable CORS per action, per controller, or globally for all Web API controllers in your application. To enable CORS for a single action, set the [EnableCors] attribute on the action method. The following example enables CORS for the GetItem method only.


2 Answers

The absolutely simplest way to get the full user-agent from inside a WebAPI-controller is by doing this:

var userAgent = Request.Headers.UserAgent.ToString(); 

It gives exactly the same result as doing the manual step like this:

// var headers = request.Headers.GetValues("User-Agent"); // var userAgent = string.Join(" ", headers); 
like image 158
Seb Nilsson Avatar answered Oct 03 '22 07:10

Seb Nilsson


.NET Core 2.0(+)

As Simple as Request.Headers["User-Agent"] (returns as string) ;)

like image 26
Alexandre Daubricourt Avatar answered Oct 03 '22 05:10

Alexandre Daubricourt