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

后端 未结 5 1945
攒了一身酷
攒了一身酷 2020-12-02 11:49

Can you please let me know how to get the browser\'s name that the client is using in MVC 6, ASP.NET 5?

5条回答
  •  情深已故
    2020-12-02 12:29

    Install this .nuget package

    create a class like this:

    public static class YauaaSingleton
        {
            private static UserAgentAnalyzer.UserAgentAnalyzerBuilder Builder { get; }
    
            private static UserAgentAnalyzer analyzer = null;
    
            public static UserAgentAnalyzer Analyzer
            {
                get
                {
                    if (analyzer == null)
                    {
                        analyzer = Builder.Build();
                    }
                    return analyzer;
                }
            }
    
            static YauaaSingleton()
            {
                Builder = UserAgentAnalyzer.NewBuilder();
                Builder.DropTests();
                Builder.DelayInitialization();
                Builder.WithCache(100);
                Builder.HideMatcherLoadStats();
                Builder.WithAllFields();
            }
    
    
        }
    

    in your controller you can read the user agent from http headers:

    string userAgent = Request.Headers?.FirstOrDefault(s => s.Key.ToLower() == "user-agent").Value;
    

    Then you can parse the user agent:

     var ua = YauaaSingleton.Analyzer.Parse(userAgent );
    
     var browserName = ua.Get(UserAgent.AGENT_NAME).GetValue();
    

    you can also get the confidence level (higher is better):

     var confidence = ua.Get(UserAgent.AGENT_NAME).GetConfidence();
    

提交回复
热议问题