隨着移動設備的流行,兼容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;
}
}