您的位置:首页 > 编程语言 > ASP

asp.net检测是否为移动设备

2015-10-09 11:46 639 查看
随着移动设备的流行,兼容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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: