casualtek
casualtek

Reputation: 541

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.

Upvotes: 48

Views: 41504

Answers (5)

Alexandre Daubricourt
Alexandre Daubricourt

Reputation: 4963

.NET Core 2.0(+)

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

Upvotes: 8

Gaurav Dubey
Gaurav Dubey

Reputation: 370

var context = new HttpContextWrapper(HttpContext.Current);
HttpRequestBase request = context.Request;
var browserdetail = request.UserAgent;

This worked for me if you want only browser name then simply write:

var browserdetail = request.browser

And if you want clients ip address then simply do:

var browserdetail = request.hostaddress and use it for generating token key for authenticaton.

Upvotes: 0

Seb Nilsson
Seb Nilsson

Reputation: 26438

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

Upvotes: 86

Cesar
Cesar

Reputation: 2369

The answer is simple try the following. It's shorter and less likely to break.

String userAgent;
userAgent = Request.UserAgent;

It will give you a string similar to this one.

Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)

Documentation: http://msdn.microsoft.com/en-us/library/system.web.httprequest.useragent.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2

Upvotes: -1

casualtek
casualtek

Reputation: 541

Oops, figured it out, answering it myself in case anyone else runs into this. Apparently the user-agent gets chopped up.

This gives me the full user-agent:

// Default empty user agent.
String userAgent = "";

// Get user agent.
if (Request.Headers.Contains("User-Agent"))
{
    var headers = request.Headers.GetValues("User-Agent");

    StringBuilder sb = new StringBuilder();

    foreach (var header in headers)
    {
        sb.Append(header);

        // Re-add spaces stripped when user agent string was split up.
        sb.Append(" ");
    }

    userAgent = sb.ToString().Trim();
}

Upvotes: 0

Related Questions