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

casualtek picture casualtek · Mar 9, 2013 · Viewed 31.7k times · Source

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.

Answer

Seb Nilsson picture Seb Nilsson · May 28, 2013

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);