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 sever
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);
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
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.
As Simple as Request.Headers["User-Agent"]
(returns as string) ;)
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();
}