ASP.NET 移动手机检测、重定向和开发变得简单
本文介绍了如何判断 HTTP 请求是否来自移动电话,然后将请求重定向到为移动浏览器优化的页面的方法。
引言
本文介绍了两种判断 HTTP 请求是否来自移动电话,然后将请求重定向到为移动浏览器优化的页面的方法。
概述
如今,几乎所有的网站都是为台式机或笔记本电脑设计的。任何运营营销、电子商务、信息或娱乐网站的人,在设计内容和服务时都需要考虑移动电话。移动网站开发日益增长,试图访问网站的不同移动设备数量也在不断增加。Web 开发人员在移动网站开发方面面临的主要问题如下:
1. 检测移动设备并重定向用户到移动网站
例如,实际客户要求:Apple 用户应重定向到 Apple 主题 URL,RIM (BlackBerry) 用户应重定向到 BlackBerry 主题 URL,所有其他移动设备都应重定向到标准移动主题 URL。
ii) 使用移动设备数据库来获取移动功能,以便为移动用户提供最佳体验
例如:该手机支持 Java 还是 Flash?或者提供哪种输入方式,例如 QWERTY 键盘还是触摸屏?
方法 1:使用 ASP.NET 检测 User-Agent
这是当今大多数 Web 开发人员使用的标准方法。使用的设备数据库是 MDBF [此项目不再支持,并于 2010 年 10 月 29 日被移除]。那么,最大的问题又来了,应该使用哪个设备数据库?哪个是最新的,并且包含广泛的移动设备信息?使用 ASP.NET 平台将服务器端浏览器检测和重定向添加到您的网站非常容易。此代码应插入到 Web 窗体代码隐藏文件(例如 default.aspx.cs)的 Page_Load
事件中。要使此功能在整个网站上生效,只需将其添加到主页文件(Master Page file)的 Page_Load
事件中即可。
方法 1
string userAgent = Request.UserAgent.ToString().ToLower();
if (userAgent != null)
{
if (Request.Browser.IsMobileDevice == true)
{
if (userAgent.Contains("iphone"))
Response.Redirect("~/Apple/Default.aspx");
else if (userAgent.Contains("nokia"))
Response.Redirect("~/Nokia/Default.aspx");
else
Response.Redirect("~/Mobile/Default.aspx");
}
}
在上面的代码中,您可以根据需要添加任意数量的用户代理。在这种情况下,else
语句不是必需的,因为我们希望在请求来自标准浏览器时页面正常加载。上述代码的局限性是:
- 它无法捕获所有移动浏览器,因为移动浏览器的数量非常多。
- 当引入新设备时,您需要不断更新用户代理。
- 不容易解析用户代理以获取有关移动设备的详细信息,例如制造商、型号、屏幕高度和宽度以及支持的图像格式。这类信息对于根据特定的移动设备定制页面布局至关重要。
这些限制让我不禁思考:“有没有更好的方法来实现这一点?” 我偶然发现了以下开源解决方案。
方法 2:使用 51degrees.codeplex.com .NET Mobile API 检测 User-Agent
51Degrees.mobi 提供了一个免费的开源 .NET Mobile API,允许 Visual Basic 和 C# 开发人员受益于 WURFL 中可用的广泛移动设备信息,WURFL 也被 BBC、Bank of America、MySpace 和 Admob 等公司使用。WURFL 设备数据库被广泛认为是目前最先进、最新的移动设备数据库。以下步骤演示了如何检测移动设备,获取准确的设备详细信息,并轻松重定向到移动登陆页面,从而克服方法 1 的局限性。
采用这种方法,无需修改现有的桌面网站页面。您只需要更新 web.config 并将几个文件复制到您的网站,如下所述。
步骤 1:使用 Visual Studio 创建现有或新的标准 ASP.NET 网站
步骤 2:下载 51Degrees.mobi 资源
需要将以下文件添加到步骤 1 中创建的网站。
- App_Data/wurfl.xml.gz
- App_Data/web_browsers_patch.xml
- bin/ FiftyOne.Foundation.dll
可以从 此处 解压这些文件。
下载后,您的网站应具有以下文件夹
步骤 3:Web.config 设置
需要将以下部分添加到您网站的 web.config 文件中,以便使用该 API。
i) 配置节
以下设置需要在 web.config 文件的顶部。它们告诉 .NET 后续的 web.config 配置以及如何处理它们。在这种情况下,我们指示 .NET 使用 Mobile 程序集。
Web.config 设置 1
<configSections>
<sectionGroup name="fiftyOne">
<section name="log" type="FiftyOne.Foundation.Mobile.Configuration.LogSection,
FiftyOne.Foundation" requirePermission="false" allowDefinition="Everywhere"
restartOnExternalChanges="false" allowExeDefinition="MachineToApplication"/>
<section name="redirect"
type="FiftyOne.Foundation.Mobile.Configuration.RedirectSection,
FiftyOne.Foundation" requirePermission="false" allowDefinition="Everywhere"
restartOnExternalChanges="false" allowExeDefinition="MachineToApplication"/>
<section name="wurfl"
type="FiftyOne.Foundation.Mobile.Detection.Wurfl.Configuration.WurflSection,
FiftyOne.Foundation" requirePermission="false" allowDefinition="Everywhere"
restartOnExternalChanges="false" allowExeDefinition="MachineToApplication"/>
</sectionGroup>
</configSections>
ii) 添加新的 <fiftyOne> 节
在 configSections
元素之后添加以下移动元素。
这些行控制 Mobile API 如何响应移动设备以及在哪里查找移动设备数据库。
Web.config 设置 2
<fiftyOne>
<!--<redirect> element controls how requests from mobile devices are handled.
mobileHomePageUrl A url to direct mobile devices to instead of the normal web sites
landing page. (Optional)
firstRequestOnly If set to true only the first request received by the web site is
redirected to the mobileUrl when the site is accessed from a mobile
device. (Optional – defaults to true)
timeout The number of minutes of inactivity that should occur before the
requesting device should be treated as making a new request to the
web site for the purposes of redirection.
If the session is available, the session timeout will be used
and override this value. (Optional
-defaults to 20 minutes)
devicesFile A file used to store the details of devices that have previously
accessed the web site to determine if they're making a subsequent
request. Needed to ensure multiple worker processes
have a consistent view of previous activity.
(Optional – random behaviour will be experienced
if not specified on web sites with more than one worker
processes)
mobilePagesRegex A regular expression that when applied to the current request Path
(context.Request.AppRelativeCurrentExecutionFilePath)
or the requesting Urlwill return true
if it should be considered a mobile page. Use this attribute
to tell redirection about mobile pages derived from base
classes such as System.Web.UI.Page. Redirection needs to be
aware of mobile pages so that requests to these pages
can be ignored. Any page
that derives from System.Web.UI.MobileControls.MobilePage will
automatically be treated as a mobile page irrespective of this
attribute. (Optional)
originalUrlAsQueryString
If set to true the redirected URL will have the original requesting
Url encoded and included as the origUrl query string parameter in
the redirected Url. This will enable the mobile home page to
determine the original requested resource
providing the option to display a mobile
friendly version. (Optional – defaults to false)
locations/location Provides details of different locations requests can be directed
to based on the values of defined properties associated with
the device or request.
(Optional)
url the URL of the redirect location to use if all the properties
in the collection match. (Mandatory)
matchExpression can be used to provide a regular expression which will take
the requesting URL as input match segments to be used
in place of numeric parameters contained
within {} in the url attribute. (Optional)
The location element contains a collection of criteria
that all need to match for the location to be used.
Two attributes must be specified with each entry.
property the property of HttpRequest, HttpRequest.Browser or
WURFL capability to use when
evaluating the matchExpression attribute. (Mandatory)
matchExpression a regular expression used to evaluate the value of the property.
(Mandatory)
-->
<redirect firstRequestOnly="true"
mobileHomePageUrl="~/Mobile/Default.aspx"
timeout="20"
devicesFile="~/App_Data/Devices.dat"
mobilePagesRegex="/(Mobile|Tablet|Apple)/">
<locations>
<!-- Don't redirect requests that have the noredirect query string parameter. -->
<location url="">
<add property="Url" matchExpression="[&|\?]noredirect"/>
</location>
<!—- Send tablets to their own home page. -->
<location url="~/Tablet/Default.aspx">
<add property="is_tablet" matchExpression="true"/>
</location>
<!—- Send iPhone to their own home page. -->
<location url="~/Apple/Default.aspx">
<add property="MobileDeviceManufacturer" matchExpression="Apple"/>
</location>
</locations>
</redirect>
<!--<log> element controls where and how much information should be
recorded in the log.
logFile The location of the log file. (Mandatory)
logLevel Values include Debug|Info|Warn|Fatal and control the level of information
logged. Defaults to Fatal if not specified. (Optional)-->
<log logFile="~/App_Data/Log.txt" logLevel="Info"/>
<!--<wurfl> element controls device data and new device handling.
wurflFilePath is the path of the main wurfl file (mandatory).
wurflPatches defines where any additional patch files can be located
(optional).
newDevicesURL provides a URL where new devices found on your server
can be recorded
(optional).
newDeviceDetail can be "minimum" or "maximum" and controls the HTTP header
information sent to location defined in newDevicesUrl (optional).
useActualDeviceRoot When set to true only Wurfl devices marked with the attribute
"actual_device_root" are used to provide capabilities.
Child devices will continue to be used to for devise matching
but their capabilities will not be used. This is an advanced
feature for those familiar with WURFL. (optional)
capabilitiesWhiteList Using the capabilityName attribute of the add elements
lists the Wurfl capabilities required by the mobile web
application. Providing this list prevents the entire list
of capabilities from being loaded slightly
improving performance.-->
<wurfl wurflFilePath="~/App_Data/wurfl.xml.gz" newDeviceDetail="maximum"
newDevicesURL=http://devices.51degrees.mobi/new.ashx
useActualDeviceRoot="false">
<capabilitiesWhiteList>
<add capabilityName="pointing_method"/>
</capabilitiesWhiteList>
<wurflPatches>
<add name="browser_definitions"
filePath="~/App_Data/web_browsers_patch.xml" enabled="true"/>
</wurflPatches>
</wurfl>
</fiftyOne>
注意: MobileDeviceManufacturer
和 is_tablet
作为属性。这些属性通过 HttpRequest 类的 Browser 属性公开。WURFL 功能和 ASP.NET 浏览器属性都可以与 property 属性一起使用。如果没有任何 <locations>
匹配,并且请求设备是移动设备,则将使用 mobileHomePageUrl
。
iii) web.config 中的 Detector Module
将以下元素添加到 httpModules
元素中。这允许 Mobile
API 拦截新页面请求,并在请求设备是移动设备时进行重定向。
Web.config 设置 3
<!-- IIS 6.0 & Visual Studio - Registers a module that is used to
detect any new requests to the web site.
Without this module mobile detection and redirection won't work.-->
<httpModules>
<add name="Detector" type="FiftyOne.Foundation.Mobile.Detection.DetectorModule,
FiftyOne.Foundation"/>
</httpModules>
<!-- IIS 7.X - Registers a module that is used to detect
any new requests to the web site.
Without this module mobile detection and redirection won't work.-->
<system.webServer>
<modules>
<remove name="Detector"/>
<add name="Detector" type="FiftyOne.Foundation.Mobile.Detection.DetectorModule,
FiftyOne.Foundation"/>
</modules>
</system.webServer>
Web.config 设置 4
<!-- To avoid errors due to Code Access Security
(CAS) the web.config defaults to set trust level to full.-->
<trust level="Full">
iii) global.asax 中的 Detector Module
最新版本 0.1.11.8 提供了另一种使用 .NET 4 和 global.asax 进行拦截的方法,这可以略微提高性能,并使 web.config 更优雅。为此,需要将以下代码放在 global.asax 中。
Global.asax 设置
#if VER4
using System;
using System.Web.Configuration;
#endif
namespace Detector
{
public class Global : System.Web.HttpApplication
{
#if VER4
protected void Application_Start(object sender, EventArgs e)
{
Enable the mobile detection provider.
HttpCapabilitiesBase.BrowserCapabilitiesProvider =
new FiftyOne.Foundation.Mobile.Detection.MobileCapabilitiesProvider();
}
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
Process redirection logic.
FiftyOne.Foundation.Mobile.Redirection.RedirectModule.
OnPostAcquireRequestState(sender, e);
}
#endif
}
}
为了使此功能正常工作,需要移除 modules 部分,并使用 VER4 编译器信号重新编译 foundation.dll。有关获取源代码的位置,请参见下文。
步骤 4:下载 Mobile Emulators 测试网站
请点击 此处 获取下载 Mobile Emulators 以测试网站的详细信息。
下载源代码
下载源代码,用于方法 2 中解释的示例应用程序。
结果
当从移动设备访问网站时,用户将被重定向到相应的移动视图。与方法 1 不同,您无需编写任何重定向代码,这由 51degrees.mobi .NET Mobile API 负责处理。此外,.NET Mobile API 还提供设备功能信息,可用于定制。它提供了对整个 WURFL 数据库的简单访问,这些数据库可以在代码中公开,如果您需要更高级的重定向(可以使用会话变量、一天中的时间或其他任何您需要的内容),这将非常有用。
访问移动功能
string capability = Request.Browser["is_tablet"];
WURFL 功能的完整列表可以在 此处 找到。
结论
如果您正在开发移动网站,并且在处理各种移动设备时遇到困难,请使用上面解释的方法 2。这将缩短开发时间,使用您可以信赖的设备数据,让您可以专注于提供出色的移动体验。
资源
历史
- 2011 年 1 月 12 日:首次发布