C# ASP.NET - 如何检测浏览器类型

C# ASP.NET - How to detect browser type

我使用 C# ASPNET 输入以下代码来检测用户使用的浏览器类型(IE、FF、Chrome、Edge)。

检测到的浏览器类型有效,但我已经验证,当代码从 Microsoft Edge 浏览器获取时,输出是

Browser Capabilities
Type = Chrome94
Name = Chrome
Version = 94.0
Major Version = 94
Minor Version = 0
Platform = WinNT
Is Beta = False
Is Crawler = False
Is AOL = False
Is Win16 = False
Is Win32 = True
Supports Frames = True
Supports Tables = True
Supports Cookies = True
Supports VBScript = False
Supports JavaScript = 3.0
Supports Java Applets = True
Supports ActiveX Controls = False
Supports JavaScript Version = 1.7

好像使用的浏览器是Google Chrome.

可能是什么问题?

下面是我的代码

System.Web.HttpBrowserCapabilities browser = Request.Browser;
string s = "Browser Capabilities\n"
    + "Type = "                    + browser.Type + "\n"
    + "Name = "                    + browser.Browser + "\n"
    + "Version = "                 + browser.Version + "\n"
    + "Major Version = "           + browser.MajorVersion + "\n"
    + "Minor Version = "           + browser.MinorVersion + "\n"
    + "Platform = "                + browser.Platform + "\n"
    + "Is Beta = "                 + browser.Beta + "\n"
    + "Is Crawler = "              + browser.Crawler + "\n"
    + "Is AOL = "                  + browser.AOL + "\n"
    + "Is Win16 = "                + browser.Win16 + "\n"
    + "Is Win32 = "                + browser.Win32 + "\n"
    + "Supports Frames = "         + browser.Frames + "\n"
    + "Supports Tables = "         + browser.Tables + "\n"
    + "Supports Cookies = "        + browser.Cookies + "\n"
    + "Supports VBScript = "       + browser.VBScript + "\n"
    + "Supports JavaScript = "     + 
        browser.EcmaScriptVersion.ToString() + "\n"
    + "Supports Java Applets = "   + browser.JavaApplets + "\n"
    + "Supports ActiveX Controls = " + browser.ActiveXControls 
          + "\n"
    + "Supports JavaScript Version = " +
        browser["JavaScriptVersion"] + "\n";

这是过去对我有用的方法:

准确的浏览器检测是使用 UserAgent 属性,如

HttpContext.Current.Request.Request.UserAgent

如果您的用户代理包含子字符串“Edg”,例如:

"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML,
like Gecko) Chrome/93.0.4577.82 Safari/537.36 Edg/93.0.961.52"

那么你的浏览器就是Edge。

如果您的用户代理包含“Chrome”,如本例所示:

"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36
(KHTML,like Gecko) Chrome/93.0.4577.82 Safari/537.36"

那么您的浏览器将是Chrome。

与本例中的 Firefox 类似:

"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:92.0) Gecko/20100101 Firefox/92.0"

一个属性我以前试过的是这个:

HttpContext.Current.Request.Browser.Browser 

这似乎是显而易见的选择,并且在很多情况下会给你正确的浏览器,但在 Edge 浏览器中,它给了我 Chrome。因此,使用 UserAgent 字符串是为 ASP.NET HTTP 请求获取浏览器的最佳方式。