首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET 識別客戶端瀏覽器與作業系統完整方案:User-Agent 解析與裝置偵測

     編輯:ASP.NET 基礎

核心方法比較

方法優點缺點適用場景
Server 端解析 User-Agent可在 Controller/Action 早期攔截、導向、記錄User-Agent 可偽造、解析邏輯需維護行動裝置導向、分析報表、安全審計
ASP.NET MVC Display Modes框架內建、View 自動切換(.Mobile.cshtml)僅支援 View 選擇、邏輯較固定響應式設計不足時的行動版 View
Client 端 JavaScript 偵測即時、可存取螢幕尺寸、觸控支援等特徵依賴 JS 執行、可被阻擋/竄改前端自適應、載入不同資源、SPA 路由導向
Request.Browser (HttpBrowserCapabilities)內建、無需額外庫資料庫較舊、無法識別新裝置簡單瀏覽器類型判斷

方案一:伺服器端 User-Agent 解析(C#)

public static class DeviceDetector
{
    private static readonly string[] MobileKeywords = 
    {
        "Mobile", "Android", "iPhone", "iPad", "iPod", "Windows Phone",
        "BlackBerry", "Opera Mini", "IEMobile", "webOS", "Kindle",
        "Silk", "Symbian", "MIDP", "J2ME", "NetFront", "UCWEB"
    };

    public static bool IsMobileDevice(string userAgent)
    {
        if (string.IsNullOrEmpty(userAgent)) return false;
        string ua = userAgent.ToLowerInvariant();
        return MobileKeywords.Any(k => ua.Contains(k.ToLowerInvariant()));
    }

    public static string GetOSName(string userAgent)
    {
        if (string.IsNullOrEmpty(userAgent)) return "未知";
        
        // Windows 版本偵測
        if (userAgent.Contains("Windows NT 10.0")) return "Windows 10";
        if (userAgent.Contains("Windows NT 6.3")) return "Windows 8.1";
        if (userAgent.Contains("Windows NT 6.2")) return "Windows 8";
        if (userAgent.Contains("Windows NT 6.1")) return "Windows 7";
        if (userAgent.Contains("Windows NT 6.0")) return "Windows Vista/Server 2008";
        if (userAgent.Contains("Windows NT 5.2")) return userAgent.Contains("64") ? "Windows XP x64/Server 2003" : "Windows Server 2003";
        if (userAgent.Contains("Windows NT 5.1")) return "Windows XP";
        if (userAgent.Contains("Windows NT 5.0")) return "Windows 2000";
        
        // 其他作業系統
        if (userAgent.Contains("Mac OS X")) return "macOS";
        if (userAgent.Contains("iPhone OS") || userAgent.Contains("iPad")) return "iOS";
        if (userAgent.Contains("Android")) return "Android";
        if (userAgent.Contains("Linux")) return "Linux";
        if (userAgent.Contains("CrOS")) return "Chrome OS";
        
        return "未知";
    }

    public static string GetBrowserName(string userAgent)
    {
        if (string.IsNullOrEmpty(userAgent)) return "未知";
        
        if (userAgent.Contains("Edg/")) return "Edge (Chromium)";
        if (userAgent.Contains("Chrome/")) return "Chrome";
        if (userAgent.Contains("Firefox/")) return "Firefox";
        if (userAgent.Contains("Safari/") && !userAgent.Contains("Chrome")) return "Safari";
        if (userAgent.Contains("MSIE") || userAgent.Contains("Trident/")) return "Internet Explorer";
        if (userAgent.Contains("Opera") || userAgent.Contains("OPR/")) return "Opera";
        
        return "未知";
    }
}

// Controller 中使用
public ActionResult Index()
{
    string ua = Request.UserAgent;
    if (DeviceDetector.IsMobileDevice(ua))
        return RedirectToAction("Index", "Mobile");
    
    ViewBag.OS = DeviceDetector.GetOSName(ua);
    ViewBag.Browser = DeviceDetector.GetBrowserName(ua);
    return View();
}

方案二:ASP.NET MVC Display Modes(內建行動裝置支援)

// Global.asax Application_Start
DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("Mobile")
{
    ContextCondition = ctx => ctx.Request.UserAgent != null && 
        DeviceDetector.IsMobileDevice(ctx.Request.UserAgent)
});

// 檢視命名慣例
// Index.cshtml         → 桌面版
// Index.Mobile.cshtml  → 行動版(自動選擇)

方案三:前端 JavaScript 偵測與導向

(function() {
    var ua = navigator.userAgent.toLowerCase();
    var isMobile = /mobile|android|iphone|ipad|windows phone|blackberry|opera mini|iemobile|symbian|midp|j2me|netfront|ucweb/.test(ua);
    
    if (isMobile) {
        // 導向行動版網站
        window.location.href = "/Mobile/Index";
    } else {
        // 桌面版邏輯
        console.log("桌面版瀏覽器");
    }
})();

方案四:使用成熟開源庫(推薦生產環境)

  1. UAParser(C# 移植版):準確解析瀏覽器、OS、裝置型號、引擎版本
  2. DeviceDetector.NET:支援數萬種裝置、Bot、爬蟲識別,定期更新規則庫
  3. 51Degrees:商業級裝置偵測,高準確度、效能佳,有免費版
// UAParser 使用範例
var parser = Parser.GetDefault();
var client = parser.Parse(Request.UserAgent);
string browser = client.UA.Family; // Chrome, Firefox...
string os = client.OS.Family;      // Windows, macOS, iOS...
string device = client.Device.Family; // iPhone, Samsung Galaxy...
bool isMobile = client.Device.IsMobile;

完整作業系統版本對照表(Windows)

User-Agent 片段作業系統
Windows NT 10.0Windows 10 / Server 2016/2019
Windows NT 6.3Windows 8.1 / Server 2012 R2
Windows NT 6.2Windows 8 / Server 2012
Windows NT 6.1Windows 7 / Server 2008 R2
Windows NT 6.0Windows Vista / Server 2008
Windows NT 5.2Windows XP x64 / Server 2003
Windows NT 5.1Windows XP
Windows NT 5.0Windows 2000

最佳實踐總結

  • 優先使用成熟庫,避免自行維護正規表達式規則
  • 伺服器端導向適合整站行動版分離架構
  • 前端偵測適合響應式微調、載入不同資源
  • 快取偵測結果(Session/Cookie),避免每請求重複解析
  • 提供使用者手動切換「桌面版/行動版」選項,尊重使用者偏好
  • 記錄 User-Agent供分析,但注意隱私法規(GDPR/個資法)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved