65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP.NET 移动设备检测

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.85/5 (22投票s)

2011年6月20日

CPOL

2分钟阅读

viewsIcon

180634

使用 ASP.NET 和 51degrees 检测最新的移动设备/浏览器

引言

在 ASP.NET 中,您可以使用 Request.Browser.IsMobileDevice 属性和 Request.UserAgent 轻松检测移动设备请求。

以下代码检查 IsMobileDevice 属性并将请求重定向到移动设备专用页面

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Browser.IsMobileDevice)
    {
       Response.Redirec("~/default_mobile.aspx");          
    }
} 

如果您从移动浏览器请求 "default.aspx",它将重定向到 default_mobile.aspx 页面

步骤 1:来自移动用户代理的请求

更改用户代理(Safari 浏览器)。

AspnetMobDeviceDetection/aspnet-mobile-detection-step2.JPG

步骤 2:请求 "default.aspx"

由于 HTTP 请求来自移动用户代理,"default.aspx" 请求会自动重定向到 "default_mobile.aspx"

AspnetMobDeviceDetection/aspnet-mobile-detection-step3.JPG

最新浏览器的问题

由于 ASP.NET 浏览器文件在 Opera Mobile 或 Android 设备上不受支持,因此某些流行的移动设备/浏览器无法通过这种方式检测到。这意味着如果您从 Opera mobile 浏览器请求 "default.aspx",它将不会重定向到 "default_mobile.aspx" Frown | :-(

AspnetMobDeviceDetection/aspnet-mobile-detection-step4.JPG

解决方案

您可以使用 51Degrees.Mobi 包解决此问题。 51Degrees.Mobi 包 是一个开源 .NET 项目,它使用来自 Wireless Universal Resource File (WURFL) 的信息增强 Request.Browser。 WURFL 是最全面和最新的移动设备信息数据库之一。

您可以使用 VS 2010 中的 NuGet 包管理器轻松安装/下载 51Degrees。

安装 51Degrees

步骤 1:打开 NuGet 包管理器

AspnetMobDeviceDetection/aspnet-mobile-detection-step5.JPG

步骤 2:安装 51Degrees

AspnetMobDeviceDetection/aspnet-mobile-detection-step6.JPG

"Install-Package 51Degrees.mobi" 命令会自动添加 "FiftyOne.Foundation.dll" 引用并将必要的文件添加到 "App_Data" 文件夹下,如下所示

AspnetMobDeviceDetection/aspnet-mobile-detection-step7.JPG

AspnetMobDeviceDetection/aspnet-mobile-detection-step8.JPG

步骤 3:定义 51Degrees 配置节

AspnetMobDeviceDetection/aspnet-mobile-detection-step9.JPG

步骤 4:定义 51Degrees/wurfl

AspnetMobDeviceDetection/aspnet-mobile-detection-step10.JPG

上述配置更改会自动更新 ASP.NET 浏览器检测功能,您可以轻松检测到现代移动设备/浏览器。 在进行此配置更改后,如果您从 Opera mobile 浏览器请求 "default.aspx",它将自动重定向到 "default_mobile.aspx" 页面,如下所示。 Smile | :)

AspnetMobDeviceDetection/aspnet-mobile-detection-step12.JPG

结论

我希望您对 51Degrees、WURFL 和 ASP.NET 浏览器检测有所了解。 感谢您的阅读。 这与我的原始帖子相同 ASP.NET 移动设备检测

© . All rights reserved.