Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get user Browser name ( user-agent ) in Asp.net Core?

People also ask

What is my User-Agent?

About What's My User Agent ToolThe tool displays the string text your web browser sends in the "User-Agent" header in the HTTP requests. The User-Agent Information identifies your browser and operating system and their versions.

What is a User-Agent header?

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 connect to User-Agent?

Select the “Advanced” tab and enable the “Show Develop menu in menu bar” option at the bottom of the window. Click Develop > User Agent and select the user agent you want to use in the list. If the user agent you want to use isn't shown here, select “Other” and you can provide a custom user agent.


I think this was an easy one. Got the answer in Request.Headers["User-Agent"].ToString()


For me Request.Headers["User-Agent"].ToString() did't help cause returning all browsers names so found following solution.

Installed ua-parse.

In controller using UAParser;

var userAgent = HttpContext.Request.Headers["User-Agent"];
var uaParser = Parser.GetDefault();
ClientInfo c = uaParser.Parse(userAgent);

after using above code was able to get browser details from userAgent by using c.UA.Family + " " + c.UA.Major +"." + c.UA.Minor You can also get OS details like c.OS.Family;

Where c.UA.Major is a browser major version and c.UA.Minor is a browser minor version.


userAgent = Request.Headers["User-Agent"]; 

https://code.msdn.microsoft.com/How-to-get-OS-and-browser-c007dbf7 (link not live) go for 4.8

https://docs.microsoft.com/en-us/dotnet/api/system.web.httprequest.useragent?view=netframework-4.8


I have developed a library to extend ASP.NET Core to support web client browser information detection at Wangkanai.Detection This should let you identity the browser name.

namespace Wangkanai.Detection
{
    /// <summary>
    /// Provides the APIs for query client access device.
    /// </summary>
    public class DetectionService : IDetectionService
    {
        public HttpContext Context { get; }
        public IUserAgent UserAgent { get; }

        public DetectionService(IServiceProvider services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            this.Context = services.GetRequiredService<IHttpContextAccessor>().HttpContext;
            this.UserAgent = CreateUserAgent(this.Context);
        }

        private IUserAgent CreateUserAgent(HttpContext context)
        {
            if (context == null) throw new ArgumentNullException(nameof(Context)); 

            return new UserAgent(Context.Request.Headers["User-Agent"].FirstOrDefault());
        }
    }
}