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

时光总嘲笑我的痴心妄想 提交于 2019-12-03 00:57:30

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

.NET Core 2.0(+)

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

casualtek

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();
}
Gaurav Dubey
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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!