Mobile Device Detection and Redirection Using ASP.NET/MVC

This article explains approaches for ASP.NET mobile development to determine if an HTTP request is coming from a mobile phone and then redirecting the request to a page optimized for a mobile browser.

Method1: Use ASP.NET To Detect The User-Agent

Adding server-side browser detection and redirection to your website using the ASP.net platform is quite easy. This code should be inserted into the Page_Load event of the web form code behind file (e.g. default.aspx.cs). To enable this site-wide, just add it to the Page_Load event of the Master Page file.

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");
  }
}
In the code above you can add as many user agents as you wish. The else statement is not necessary in this case, because we want the page to load normally, when the request is coming from standard browsers.

Limitations of above code are:
  • It will not catch all mobile browsers as there are a lot of them.
  • You need to keep updating user agents when new devices are introduced.
  • Not easy to parse user agents to get detailed information about the mobile device such as the manufacturer, model, screen height & width, and image formats supported. This type of information is necessary to customize page layout to the specific mobile device.


These limitations made me ask "is there any better way to achieve this? I came across the following method.

Method2.1: Use 51Degrees.mobi .NET Mobile API To Detect The User-Agent

51Degrees.mobi provides a free open source ASP.NET mobile API allowing Visual Basic and C# developers to benefit from the extensive mobile device information available in WURFL also used by the BBC, Bank of America, MySpace and Admob among others. WURFL device database is widely-accepted as the most advanced and up-to-date mobile device database available.

The following steps demonstrate how to detect a mobile device, obtain accurate device details and easily redirect to a mobile landing page overcoming the limitations of Method 1.

Step 1: Create Web Site

Note:
Visual Studio 2008 default installation does not have "Mobile Web Form" template. To develop mobile web applications the necessary templates need to be installed. To install these templates download them from this Visual Web Developer Team Blog Post, extract the ZIP file, and follow the instructions in the included readme.txt files attached to each of the extracted Zip folders. Once installed please perform the following steps. Visual Studio 2005 users do not require installing these templates as they are already installed.

i) Create a C# ASP.NET website.
ii) The website will be created with a default web form "Default.aspx", keep the name as it is.
iii) Add a Mobile Web Form to the website using "Add New Item -> Mobile Web Form". Name the mobile web form to "M.aspx"

Step 2: 51Degrees.mobi resource download

Following files need to be added to the web site created in Step 1.
  • App_Data/wurfl.xml.gz
  • App_Data/web_browsers_patch.xml.gz
  • bin/Mobile.dll

These files can be extracted from the Enhance download available here.

Once downloaded your website should have following folder structure.


Figure 01: The Website Folder Structure

Step 3: Web.config Settings

Following sections need to be added to the web.config file of your web site to make use of the API

i) Configuration section:

The following settings are needed at the top of the web.config file. They tell .NET about subsequent configurations in the web.config and how to handle them. In this instance we're telling .NET to use the Mobile assembly.

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>
Note: The version number 0.1.5.0 should be changed to match the version of the Mobile.dll assembly you're using. All other sections should remain unchanged

ii) Add new mobile section:

Add the following mobile element after the configSections element. These lines control how the Mobile API responds to mobile devices and where to locate the database of mobile devices.

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>
iii) Detector Module:

Add the following element to the httpModules element. These allow the Mobile API to intercept new page requests and redirect them if the requesting device is a mobile.

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>
Note: The version number 0.1.5.0 should be changed to match the version of the Mobile.dll assembly you're using. All other sections should remain unchanged

Step4: Mobile Page (M.aspx)

Add the following code to M.aspx and 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. } }
Step5: Build the Website using "Build -> Build Web Site" menu

Step6: Download Mobile Emulators To Test Web site

Please click here to get details for downloading Mobile Emulators to test website.

Result:
When the website is accessed from a Mobile Emulator it will automatically display "M.aspx" to the user instead of "Default.aspx". Unlike Method1 you do not have to write any code for redirection, it is taken care by the 51degrees.mobi .NET Mobile API. Apart from this .NET Mobile API also gives information of device capabilities which can you used for customization.



Download:
To download source code for the above sample application explained in Method2.1 please click VS2005 VS2008

Method2.2: Use 51Degrees.mobi .NET Mobile API To Detect The User-Agent [MVC]

I'm going to use a simple application to help illustrate how 51Degrees.mobi ASP.NET mobile API can be used in an ASP.NET MVC application to detect mobile device capabilities.

Note:
You'll need either Visual Studio 2008 or Visual Web Developer 2008 Express to build an ASP.NET MVC application. You also need to download the ASP.NET MVC framework from http://www.asp.net/mvc/download/


Step1: Create A New ASP.NET MVC Application

The ASP.NET MVC Framework includes Visual Studio Project Templates that make it easy to create a new web application with it. Simply select the File->New Project menu item and choose the "ASP.NET MVC Web Application" template to create a new web application using it.


Figure 03: The New Project dialog box

Note:
Make sure that you select .NET Framework 3.5 from the dropdown list at the top of the New Project dialog or the ASP.NET MVC Web Application project template won't appear.


Whenever you create a new MVC Web Application project, Visual Studio prompts you to create a separate unit test project (see Figure 04). Because we won't be creating tests in this article select the No option and click the OK button.


Figure 04: Create Unit Test Project dialog

When you create a new ASP.NET MVC application with Visual Studio, you get a sample application by default. It has a standard set of folders: a Models, Views, and Controllers folder. You can see this standard set of folders in the Solution Explorer window (see Figure 05).


Figure 05: MVC Application Default Folder Structure

We'll need to add files/folders to Views and Controllers folders in order to build the Mobile device detection application.

In the Solution Explorer window, right-click the Views folder and select the menu option Add, New Folder. Name the new folder as Mobile (see Figure 06).


Figure 06: A New Mobile View Folder

Step2: 51Degrees.mobi resource download

Note: Same as explained for Method 2.1 above.

Step3: Web.config Settings

Following sections need to be added to the web.config file of your web site to make use of the API

i) Configuration section:

Note: Same as explained for Method 2.1 above.

ii) Add new mobile section:

Add the following mobile element after the configSections element. These lines control how the Mobile API responds to mobile devices and where to locate the database of mobile devices.

<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>
iii) Detector Module:

Note: Same as explained for Method 2.1 above.

Step4: Creating The ASP.NET MVC Controller

The next step is to create the ASP.NET MVC controller. A controller is responsible for controlling how a user interacts with an ASP.NET MVC application.

Follow these steps:

  1. In the Solution Explorer window, right-click the Controllers folder and select the menu option Add, Controller.
  2. In the Add Controller dialog, enter the name MobileController and do not check the checkbox labeled Add action methods for Create, Update, and Details scenarios (see Figure 06).
  3. Click the Add button to add the new controller to your project.

Figure 07:Adding a new ASP.NET MVC Controller

Listing: 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(); } } }
Now we need ASP.NET MVC to look for different views if the device is a mobile. Add following code to HomeController.cs in order to load views optimized for mobile.

Listing: 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(); }
Step 5: Creating The ASP.NET MVC View

The Index() method in the MobileController.cs returns a view named Index under Views-> Mobile folder. We need to create this view for mobiles apart from Nokia, Iphone and Blackberry.

Follow these steps:
i) Right-click the Index() method in the code editor and select the menu option Add View (see Figure 08).
ii) In the Add View dialog, verify that the none of the checkboxes are checked (see Figure 09).


Figure 08: Adding a view from controller action


Figure 09: Creating a new view with the Add View dialog

After you complete these steps, a new view named Index.aspx is added to the Views\Mobile folder. Follow same steps for methods Nokia(),Iphone() and Blackberry() to create views (see Figure 10).


Figure 10: Views->Mobile folder structure

The contents of the Index view are included in below Listing.
Listing: 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>
Use the same method to add the html code for the views Nokia.aspx, Iphone.aspx and BlackBerry.aspx. You can find code from the sample application attached to this article (see below for download link).

Step 6: Build the Application using Build menu

Step 7: Download Mobile Emulators To Test Web site
Please click here to get details for downloading Mobile Emulators to test website.

Result:
When the website is accessed it will check whether it is accessed from mobile device or desktop/laptop. If it is accessed from a desktop/laptop than Views\Home\Index.aspx view will be dispalyed. If it is accessed from mobile a device a view optimized for requesting mobile device will be displayed. e.g. If requesting mobile device is Nokia than Views\Mobile\Nokia.aspx will be displayed.

51Degrees.mobi gives detailed capability information(like manufacturer, model, screen height & width, image supports and many more) of the mobile requesting website which can be very handy for designing ASP.NET MVC Views for different device family (Nokia, Iphone, Blackberry etc.).


Figure 11: Different MVC views loaded for different devices with device capability information.

Download:
To download source code for the above sample MVC application explained in Method2.2 please click here

Conclusion:
If you're developing mobile websites and struggling with the variety of mobile devices use Method2.1 or Method2.2 as explained above. It will reduce development time, uses device data you can trust and leaves you free to focus on delivering an amazing mobile experience. Both methods will detect network transcoders and detect devices extremely quickly. Method 2.1 will work with .NET version 2.0 and above allowing mobile pages to be developed alongside existing sites without requiring an upgrade. Method 2.2 works with MVC and .NET version 3.5 and above allowing you to use Microsoft's latest technologies.

Resource:
i) Click here for more details on .NETMobile API.
ii) Click here for detailed information on web.config settings for .NETMobile API usage.


Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date