现在的位置: 首页 > 综合 > 正文

ASP.NET 根据 UserAgent 获取浏览器的类型和版本

2011年06月09日 ⁄ 综合 ⁄ 共 1434字 ⁄ 字号 评论关闭
//using System.Text.RegularExpressions;
public string GetBrowserName(string userAgent, out string browserName, out string ver)
{
    string fullBrowserName = string.Empty;
    browserName = string.Empty;
    ver = string.Empty;
    // IE
    string regexStr = @"msie (?<ver>[\d.]+)";
    Regex r = new Regex(regexStr, RegexOptions.IgnoreCase);
    Match m = r.Match(userAgent);
    if (m.Success)
    {
        browserName = "IE";
        ver = m.Groups["ver"].Value;
        fullBrowserName = string.Format("{0} {1}", browserName, ver);
        return fullBrowserName;
    }
    // Firefox
    regexStr = @"firefox\/([\d.]+)";
    r = new Regex(regexStr, RegexOptions.IgnoreCase);
    m = r.Match(userAgent);
    if (m.Success)
    {
        browserName = "IE";
        ver = m.Groups["ver"].Value;
        fullBrowserName = string.Format("{0} {1}", browserName, ver);
        return fullBrowserName;
    }
    // Chrome
    regexStr = @"chrome\/([\d.]+)";
    r = new Regex(regexStr, RegexOptions.IgnoreCase);
    m = r.Match(userAgent);
    if (m.Success)
    {
        browserName = "IE";
        ver = m.Groups["ver"].Value;
        fullBrowserName = string.Format("{0} {1}", browserName, ver);
        return fullBrowserName;
    }
    // Opera
    regexStr = @"opera.([\d.]+)";
    r = new Regex(regexStr, RegexOptions.IgnoreCase);
    m = r.Match(userAgent);
    if (m.Success)
    {
        browserName = "IE";
        ver = m.Groups["ver"].Value;
        fullBrowserName = string.Format("{0} {1}", browserName, ver);
        return fullBrowserName;
    }
    // Safari
    regexStr = @"version\/([\d.]+).*safari";
    r = new Regex(regexStr, RegexOptions.IgnoreCase);
    m = r.Match(userAgent);
    if (m.Success)
    {
        browserName = "IE";
        ver = m.Groups["ver"].Value;
        fullBrowserName = string.Format("{0} {1}", browserName, ver);
        return fullBrowserName;
    }
    return fullBrowserName;
}

 

抱歉!评论已关闭.