asp.net檢測是否為移動裝置
阿新 • • 發佈:2019-02-11
隨著移動裝置的流行,相容web的專案的需求,不斷的增加,那麼我們怎麼樣判斷,是否為移動端裝置請求的服務端呢,asp.net為我們提供了這樣的寫法:
string strUserAgent = Request.UserAgent.ToString().ToLower(); if (strUserAgent != null) { if (Request.Browser.IsMobileDevice == true || strUserAgent.Contains("iphone") || strUserAgent.Contains("blackberry") || strUserAgent.Contains("mobile") || strUserAgent.Contains("windows ce") || strUserAgent.Contains("opera mini") || strUserAgent.Contains("palm")) { //請求處理 } }
還有一種正則的判斷方法:
web.config或者app.config:
<appSettings> <!-- 這是一個正則表示式,用來標識移動裝置。被識別出的移動裝置將採用移動版的主題模板 --> <add key="BlogEngine.MobileDevices" value="(iemobile|iphone|ipod|android|nokia|sonyericsson|blackberry|samsung|sec\-|windows ce|motorola|mot\-|up.b|midp\-)"/> </appSettings>
c#程式碼:
/// <summary> /// The regex mobile. /// </summary> private static readonly Regex RegexMobile = new Regex( ConfigurationManager.AppSettings.Get("BlogEngine.MobileDevices"), RegexOptions.IgnoreCase | RegexOptions.Compiled); /// <summary> /// Gets a value indicating whether the client is a mobile device. /// </summary> /// <value><c>true</c> if this instance is mobile; otherwise, <c>false</c>.</value> public static bool IsMobile { get { var context = HttpContext.Current; if (context != null) { var request = context.Request; if (request.Browser.IsMobileDevice) { return true; } if (!string.IsNullOrEmpty(request.UserAgent) && RegexMobile.IsMatch(request.UserAgent)) { return true; } } return false; } }