我想在ASP.NET页面上使用C#确定代码隐藏文件中的浏览器类型。
如果它是IE 6.0
,我必须执行某些代码行。
如何确定浏览器类型?
您可以使用Request.Browser来识别浏览器信息。这些MSDN 1和2文章提供了更多信息。
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";
您可能还想查看:Request.ServerVariables。
我用过:
string UserAgent = Request.ServerVariables["HTTP_USER_AGENT"];
Response.Write("User: " + UserAgent);
if(UserAgent.Contains("MSIE")) {
//do something
}
向我展示正在使用的浏览器。这可以给你一个类似于IE的响应:
User: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.21022; Tablet PC 2.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.1.4322)
取决于您的IE或其他浏览器的版本。 Firefox给了我:
User: Mozilla/5.0 (Windows NT 6.0; rv:11.0) Gecko/20100101 Firefox/11.0
重要的是要注意:我会使用ServerVariables而不是浏览器功能,因为在Chrome上使用BrowserCapabilities目前会返回“桌面”,当我在Mac上查看它时,它似乎与Safari相同。
这应列出所有浏览器功能......
System.Web.HttpBrowserCapabilities browser = Request.Browser;
IDictionaryEnumerator enumerator = browser.Capabilities.GetEnumerator();
while (enumerator.MoveNext())
{
string key = (string)enumerator.Key.ToString();
object value = enumerator.Value;
Response.Write(String.Format("Key = {0}, Value = {1}", key, value));
}
由于Request是页面类的属性,上面的代码给了我错误请求不存在我使用以下代码来获取浏览器类型
private string GetBrowserType()
{
string browserType = string.Empty;
if (HttpContext.Current != null)
{
var request = HttpContext.Current.Request;
browserType = request.Browser.Type;
}
return browserType;
}
它给了我Chrome64
与Chrome和InternetExplorer11
与IE