技术开发 频道

使用ASP.NET MVC检测、重定向移动设备

  【IT168 专稿】本文向大家介绍利用ASP.NET进行移动开发的各种方法,用以确定一个HTTP请求是否来自移动电话,如果是则将其重定向到专门为移动浏览器做过优化的页面。

  方法1:使用ASP.NET检测User-Agent

  使用ASP.net平台为我们的站点添加服务器端浏览器检测和重定向功能是件非常容易的事情。下面的代码可以插入有关文件(例如default.aspx.cs)Web表单代码的Page_Load事件中。要想使其在全站内生效,只需将其添加到母版页(Master Page)文件的Page_Load事件之内即可。

  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"))
  {
  Response.Redirect(
"DefaultMobile.aspx");
  }
  }

   在以上代码中,我们可以随意添加用户代理。本例中,else语句不是必需的,因为如果请求是来自标准浏览器的话,我们想让该页正常加载。

  以上代码的局限性:

  它没有捕捉所有的移动浏览器,这里只是其中一部分。

  当新的设备被引入时,我们需要更新用户代理。

  不便于解析用户代理以获得移动设备详细信息,如制造商、模式、屏幕尺寸以及所支持的图像格式等。这些信息是为特定移动设备定制页面布局所必不可少的内容。

  既然有这些局限性,您可能会问:有没有更好的方法来达到我们的目的?答案是肯定的,具体方法如下所示。

  方法2:使用.NET Mobile API即51Degrees.mobi检测User-Agent

  51Degrees.mobi提供了一个免费开源的ASP.NET移动应用程序编程接口,允许Visual Basic和C#开发人员来利用WURFL中各种广泛的移动设备信息;目前,BBC、Bank of America、MySpace 和Admob等组织已经在使用这个编程接口。WURFL设备数据库是目前公认的非常先进、最新的移动设备数据库。

  以下步骤示范如何检测移动设备,如何获得精确的设备详细资料,并将其轻松重定向到一个移动设备着陆页面。这里已经很好地克服了方法1的局限性。

  步骤1:创建web站点

  注意:Visual Studio 2008默认安装没有“Mobile Web Form”模板,但是,为了开发移动web应用程序,我们必须安装一些模板。 为了安装这些模板,可以从Visual Web Developer Team Blog中下载它们,然后解压ZIP文件,并按照每个Zip文件夹中的自述文件进行安装。一旦安装完毕,就可以进行下面的步骤了。 Visual studio用户无需安装这些模板,因为它们早就安装好了。

  ·创建一个C# ASP.NET 网站。

  ·该网站将使用默认Web窗体“default.aspx”创建,名称可以保持不变。

  ·通过“Add New Item -> Mobile Web Form”为该网站添加Mobile Web Form。 将这个移动web窗体命名为“M.aspx”。

  步骤2:下载51Degrees.mobi资源

  对于步骤1中创建的web站点,还需添加如下所示的文件:

  App_Data/wurfl.xml.gz

  App_Data/web_browsers_patch.xml.gz

  bin/Mobile.dll

  这些文件下列地址:http://www.51degrees.mobi/LinkClick.aspx?fileticket=bkGhrKfBMgM%3d&tabid=112处下载。

  下载完成后,我们的网站应该具有如下所示的文件夹结构。


图1 网站的文件夹结构

  步骤3:设置web.config

  为了利用API,需要为web.config文件添加下面的内容。

  (1)Configuration部分:

  以下设置需要放置在web.config文件的顶部。它们通知.NET在web.config中后续配置的有关信息,以及如何处理它们。在本例中,我们告诉.NET要使用Mobile程序集。

  Web.config Setting1:
<configSections>
  
<sectionGroup name="mobile">
      
<section name="toolkit" type="Mobile.Configuration.ToolkitSection, Mobile,
                  Version=0.1.5.0, Culture=neutral"
allowDefinition="Everywhere"
                  restartOnExternalChanges
="false" allowExeDefinition="MachineToApplication"/>
      
<section name="wurfl" type="Mobile.Devices.Wurfl.Configuration.WurflSection, Mobile,
                   Version=0.1.5.0, Culture=neutral"
allowDefinition="Everywhere"
                   restartOnExternalChanges
="false" allowExeDefinition="MachineToApplication"/>
  
</sectionGroup>
</configSections>

   注意:版本号0.1.5.0应该改成你使用的Mobile.dll的版本号。其它部分无需修改。

  (2)添加新的mobile部分:

  在configSections元素之后添加如下所示的mobile元素。这些代码管理Mobile API对移动设备的响应方式,以及从哪里寻找移动设备的数据库。

Web.config Setting2:
<mobile>
  
  
<!-- When a mobile device is found to be accessing a non mobile page the
      mobileRedirectUrl setting is used to redirect the browser to a landing
      page for mobile devices.
-->
  
<toolkit mobileRedirectUrl="~/M.aspx" logFile="~/App_Data/Log.txt" logLevel="Info"/>
  
  
<!-- The following settings provided the location of wurfl files. wurflFilePath
      is the path of the main wurfl file (mandatory). newDevicesPatchFile shows where
      devices that aren't matched exactly should be stored (optional). wurflPatches
      defines where any additional patch files can be located (optional).
-->
  
<wurfl wurflFilePath="~/App_Data/wurfl.xml.gz">
      
<wurflPatches>
        
<add name="browser_definitions"
                 filePath
="~/App_Data/web_browsers_patch.xml.gz"
                 enabled
="true"/>
      
</wurflPatches>
  
</wurfl>
</mobile>

    (3)Detector模块:

  将下面的元素添加到httpModules元素中,这允许Mobile API拦截新的页面请求,并且如果请求时移动设备发出的话,就重定向它们。

Web.config Setting3:

<httpModules>
  
<!-- 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.
-->
  
<add name="Detector" type="Mobile.Browser.Detector, Mobile, Version=0.1.5.0"/>
</httpModules>

   注意:版本号0.1.5.0应该改成你使用的Mobile.dll的版本号。其它部分无需修改。

  步骤4:移动页面(M.aspx)

  将以下代码添加到M.aspx和M.aspx.cs中:

  M.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="M.aspx.cs" Inherits="M" %>
<%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %>

<html xmlns="http://www.w3.org/1999/xhtml"
<body
>
  
<mobile:Form id="Form1" runat="server">
      
<mobile:Label ID="LabelMobile" Runat="server" Alignment="Center" Font-Size="Large"
                    Text
="This is a Mobile Device Redirection." />
      
<mobile:Label ID="LabelManufacturer" Runat="server" Alignment="Center" Font-Size="Normal"/>
      
<mobile:Label ID="LabelModel" Runat="server" Alignment="Center" Font-Size="Normal"/>
      
<mobile:Label ID="LabelScreen" Runat="server" Alignment="Center" Font-Size="Normal"/>
      
<mobile:Label ID="LabelPlatform" Runat="server" Alignment="Center" Font-Size="Normal"/>
      
<mobile:Label ID="LabelBrowser" Runat="server" Alignment="Center" Font-Size="Normal"/>
      
<mobile:Label ID="LabelJpg" Runat="server" Alignment="Center" Font-Size="Normal"/>
      
<mobile:Label ID="LabelPng" Runat="server" Alignment="Center" Font-Size="Normal"/>
      
<mobile:Label ID="LabelGif" Runat="server" Alignment="Center" Font-Size="Normal"/>
  
</mobile:Form>
</body>
</html>

   M.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Mobile;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.MobileControls;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class M : System.Web.UI.MobileControls.MobilePage
{
  
protected void Page_Load(object sender, EventArgs e)
  {
    
string strUserAgent = Request.UserAgent;
     LabelManufacturer.Text
= "Manufacturer : " + Request.Browser.MobileDeviceManufacturer;
     LabelModel.Text
= "Model : " + Request.Browser.MobileDeviceModel;
     LabelScreen.Text
= "Screen : " + Request.Browser.ScreenPixelsWidth.ToString() +
                        
" x " + Request.Browser.ScreenPixelsHeight.ToString();

    
//Apart from standard capability information provided by "Request.Browser object",
    
//.NETMobileAPI provides more detailed information about the device capabilities.
     LabelPlatform.Text = "Platform : " + Mobile.Devices.MobileDevices.GetCapability(strUserAgent, "device_os");
     LabelBrowser.Text
= "Browser : " + Mobile.Devices.MobileDevices.GetCapability(strUserAgent, "mobile_browser");
     LabelJpg.Text
= "Jpg Image : " + Mobile.Devices.MobileDevices.GetCapability(strUserAgent, "jpg");
     LabelPng.Text
= "Png Image : " + Mobile.Devices.MobileDevices.GetCapability(strUserAgent, "png");
     LabelGif.Text
= "Gif Image : " + Mobile.Devices.MobileDevices.GetCapability(strUserAgent, "gif");

    
//Note: For more capabilities please refer to App_Data/Capabilities.xml file.
  }
}

  步骤5:使用“Build -> Build Web Site”菜单建立网站。

  步骤6:下载移动设备模拟器以测试web站点。

  要想获得下载移动设备模拟器以测试网站的详细信息,请访问地址:http://www.51degrees.mobi/Products/MobileEmulators/tabid/87/Default.aspx。

  结果:

  从Mobile Emulator访问该网站时,网站会自动为用户显示M.aspx,而非Default.aspx页面。 与方法1不同的是,我们不必为重定向编写任何代码,因为这是51Degrees.mobi的活儿。此外,这个.NET Mobile API还会提供可用于进行定制的设备能力信息。

  下载:

  对于以上示例应用程序的源代码,下载地址如下所示:

  对于VS 2005:http://51degrees.mobi/Portals/mcro/External/Articles/MobileWebVS2005.zip 对于VS 2008:http://51degrees.mobi/Portals/mcro/External/Articles/MobileWebVS2008.zip。

  方法3:使用.NET Mobile API即51Degrees.mobi检测User-Agent[MVC]

  下面,我们通过一个简单的应用程序来演示如何在ASP.NET MVC应用程序中使用ASP.NET的移动应用编程接口51Degrees.mobi来检测移动设备的各种功能。

  注意:为了构建ASP.NET MVC应用程序,我们需要使用Visual Studio 2008或者Visual Web Developer 2008 Express。此外,我们还需下载ASP.NET MVC框架,地址为http://www.asp.net/mvc/download/。

  步骤1:创建一个新的ASP.NET MVC应用程序

  ASP.NET MVC框架包含了许多Visual Studio项目模板,利用这些模板可以简化创建新的web应用程序的过程。只有选择“File->New Project”菜单项,然后选择“ASP.NET MVC web application”模板来新建一个web应用。


图3 新建项目对话框

  注意:确保选中了新建项目对话框顶部下拉列表中的.NET Framework 3.5,否则就无法找到ASP.NET MVCweb应用项目模板。

  每当创建一个新的MVC web应用项目时,Visual Studio就会提示我们创建一个单独的单元测试项目(参见图04)。 由于我们这里不打算进行测试,因此选择No选项,并单击OK按钮。


图4 创建单元测试项目对话框

  当利用Visual Studio创建一个新的ASP.NET MVC应用程序时,在默认情形下会得到一个示例应用程序。它具有一组标准的文件夹,分别为Models、Views 和Controllers文件夹。 在Solution Explorer窗口中,我们能够看到这组标准的文件夹(参见图05)。


图5 MVC应用程序的默认文件夹结构

  为了建立移动设备检测应用程序,我们需要向Views和Controllers文件夹中添加一些文件/文件夹。

  在Solution Explorer窗口中,右键单击Views文件夹并选择菜单选项Add、New Folder。将新建文件夹命名为Mobile(参见图06)。


图6 新建视图文件夹Mobile

  步骤2:下载51Degrees.mobi资源

  步骤3:设置web.config

  为了利用API,需要为web.config文件添加下面的内容。

  (1)Configuration部分:

  注意事项同方法2。

  (2)添加新的mobile部分:

  在configSections元素之后添加如下所示的mobile元素。这些代码管理Mobile API对移动设备的响应方式,以及从哪里寻找移动设备的数据库。

<mobile>
    
<!-- The following settings provided the location of wurfl files.
        wurflFilePath is the path of the main wurfl file (mandatory).
        newDevicesPatchFile shows where devices that aren't matched exactly
        should be stored (optional). wurflPatches defines where any
        additional patch files can be located (optional).
-->
    
<wurfl wurflFilePath="~/App_Data/wurfl.xml.gz">
        
<wurflPatches>
            
<add name="browser_definitions" filePath="~/App_Data/web_browsers_patch.xml.gz" enabled="true"/>
        
</wurflPatches>
    
</wurfl>
</mobile>

   (3)Detector模块:

  注意事项同方法2。

  步骤4:创建ASP.NET MVC控制器

  下一步是创建ASP.NET MVC控制器。控制器的作用是负责控制用户和ASP.NET MVC应用程序之间的交互方式。

  具体可参照以下步骤:

  ⒈ 在Solution Explorer窗口中,右键单击Controllers文件夹并选择菜单选项Add、Controller。

  2. 在Add Controller对话框中,输入名称MobileController,但是不要选择标为“Add action methods for Create, Update, and Details scenarios。”的复选框(参见图06)。

  3. 单击Add按钮,为项目添加新的控制器。


图7 添加新的ASP.NET MVC控制器

  清单:Controllers\MobileController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace MVCMobileDetect.Controllers
{
    
public class MobileController : Controller
    {
        
//
        
// GET: /Mobile/
        public ActionResult Index()
        {
            
return View();
        }

        
public ActionResult Nokia()
        {
            
return View();
        }

        
public ActionResult Iphone()
        {
            
return View();
        }

        
public ActionResult Blackberry()
        {
            
return View();
        }
    }
}

  现在,我们需要根据设备是否为移动设备来让ASP.NET MVC查找不同的视图。为了装入为移动设备优化过的视图,需要向HomeController.cs添加下列代码。

  清单:Controllers\HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCMobileDetect.Controllers
{
    [HandleError]
    
public class HomeController : Controller
    {
        
public ActionResult Index()
        {
            ViewData[
"Message"] = "Welcome to ASP.NET MVC!";
            
if (Request.Browser.IsMobileDevice)
            {
                
string strmanu = Request.Browser.MobileDeviceManufacturer.ToLower().ToString();
                
string straction = "";
                
string strcontrol = "Mobile";
                
switch (strmanu)
                {
                    
case "nokia":
                        straction
= "Nokia";
                        
break;
                    
case "rim":
                        straction
= "Blackberry";
                        
break;
                    
case "apple":
                        straction
= "Iphone";
                        
break;
                    
default:
                        straction
= "Index";
                        
break;
                }
                
return RedirectToAction(straction, strcontrol);
            }
            
else
                
return View();
        }

        
public ActionResult About()
        {
            
return View();
        }

   步骤5:创建ASP.NET MVC视图

  MobileController.cs中的Index()方法将返回一个名为Index的视图,该视图位于Views->Mobile文件夹中。我们需要为Nokia、Iphone和Blackberry之外的移动设备创建这个视图。

  具体可参照以下步骤:

  (1)在代码编辑器中右键单击Index()方法,并选择菜单选项Add View(参见图08)。

  (2)在Add View对话框中,不要选择任何复选框(参见图09)。


图8 从控制器动作中添加一个视图


图9 利用Add View对话框创建新视图

  完成上述步骤之后,一个名为Index.aspx的新视图将添加到Views\Mobile文件夹。对于Nokia()、Iphone()和Blackberry(),可以执行同样的步骤来创建视图(参见图10)。


图10 Views->Mobile文件夹结构

  Index视图的内容如下面的清单所示。

  清单:Views\Mobile\Index.aspx

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>MVC Mobile Sample</title>
</head>
<body>
    
<div align="center"><img src="/images/mobile.jpg" width="60" height="70" /></div>
    
<div>
        
<h6>Manufacturer : <%= Request.Browser.MobileDeviceManufacturer %></h6>
        
<h6>Model : <%= Request.Browser.MobileDeviceModel%></h6>
        
<h6>Screen : <%= Request.Browser.ScreenPixelsWidth + " x " + Request.Browser.ScreenPixelsHeight %></h6>

        
<!--Apart from standard capability information provided by "Request.Browser object",
            .NETMobileAPI provides more detailed information about the device capabilities.
-->
        
<h6>Platform : <%= Mobile.Devices.MobileDevices.GetCapability(Request.UserAgent, "device_os")%></h6>
        
<h6>Browser : <%= Mobile.Devices.MobileDevices.GetCapability(Request.UserAgent, "mobile_browser")%></h6>
        
<h6>Jpg Image : <%= Mobile.Devices.MobileDevices.GetCapability(Request.UserAgent, "jpg")%></h6>
        
<h6>Png Image : <%= Mobile.Devices.MobileDevices.GetCapability(Request.UserAgent, "png")%></h6>
        
<h6>Gif Image : <%= Mobile.Devices.MobileDevices.GetCapability(Request.UserAgent, "gif")%></h6>
        
<!--Note: For more capabilities please refer to App_Data/Capabilities.xml file.-->
    
</div>
</body>
</html>

   使用相同的方法为Nokia.aspx、Iphone.aspx和BlackBerry.aspx视图添加html代码。这些代码可以从本文附带的示例应用程序中找到(下载链接见后面)。

  步骤6:使用Build菜单构建应用程序

  步骤7:下载移动设备模拟器以测试web站点。

  要想获得下载移动设备模拟器以测试网站的详细信息,请访问地址:http://www.51degrees.mobi/Products/MobileEmulators/tabid/87/Default.aspx。

  结果:

  当网站接受访问时,它会检查该访问是来自移动设备还是来自桌面/便携式计算机。如果访问是来自桌面/便携式计算机,那么将向其展示Views\Home\Index.aspx视图。如果访问来自一个移动设备,那么就像该设备展示专门为其做过优化的视图。比如,如果访问网站的移动设备为Nokia,那么就给它返回Views\Mobile\Nokia.aspx页面。

  51Degrees.mobi能够提供访问网站的移动设备的详细信息,如制造商、模式、屏幕尺寸、所支持的图像格式等等,这些信息对于为不同的设备系列(Nokia、Iphone、Blackberry 等等)设计不同的ASP.NET MVC视图非常有用。


图11 根据设备性能信息为不同的设备加载不同的MVC视图

  下载:

  上面示例MVC应用程序的完整源代码下载地址为http://51degrees.mobi/Portals/mcro/External/Articles/MVCMobileDetect.zip。

  结束语

  如果您正在开发移动网站并努力应付移动设备的多样性的话,不妨借鉴一下本文介绍的方法2.1或者方法2.2。这不仅能减少开发时间,同时还可以使用设备数据为移动用户带来令人惊讶的用户体验。 这些方法都会极其迅速地检查网络转码器和设备。 方法2.1用到2.0及更高版本的.NET环境,它能够为现有站点并行开发移动网页,而无需进行任何升级。方法2.2需要用到MVC和3.5及更高版本的.NET环境,这允许使用微软公司的最新技术。

0
相关文章