Click here to Skip to main content
Click here to Skip to main content

ASP.NET Mobile Handset Detection, Redirection & Development Made Easy

, 12 Jan 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
This article explains approaches 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.

Introduction

This article explains two approaches 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.

Overview

Today, almost all web sites are designed to operate on a desktop or laptop computer. Anyone operating marketing, ecommerce, information or entertainment web sites now needs to consider the mobile phone when designing content and services. Mobile web sites development is increasing day by day and so is the number of different mobile devices trying to access the web sites. Major problems for web developers for mobile website development are following:

1. Detect mobile device and redirect user to mobile website

E.g. Practical client requirement: Apple users should be redirected to an Apple theme URL, RIM (BlackBerry) users should be redirected to a Blackberry theme URL and all other mobile devices should be redirected to a standard mobile theme URL.

ii) Mobile device database to fetch mobile capabilities in order to deliver the best possible experience to mobile users

E.g. Does this phone support Java or Flash, or what kind of entry method is available, such as a qwerty keyboard or a touch screen?

Approach 1: Use ASP.NET to Detect The User-Agent

It is the standard method used by most of the web developers today. Device database used is MDBF [This project is no longer supported and is removed on October 29, 2010]. So the big question again, which device database to use, which is up to date, and has a wide range of mobile device information? 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.

Approach 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");
	}       
 } 

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 the 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 open source solution.

Approach 2: Use 51degrees.codeplex.com .NET Mobile API To Detect The User-Agent

51Degrees.mobi provides a free open source .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 Approach 1.

With this approach, there is no need to update your existing web pages of desktop website. You just need to update web.config and copy couple of files to your website as explained below.

Step 1: Use existing or create new standard ASP.NET web site using Visual Studio

Step 2: 51Degrees.mobi resource download

The 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
  • bin/ FiftyOne.Foundation.dll

These files can be extracted from here.

Once downloaded, your website should have the following folders:
3.jpg

Step 3: Web.config Settings

The 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 Setting 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) Add new <fiftyOne> 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 Setting 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> 

Note: In this example, MobileDeviceManufacturer and is_tablet is used as the property. These properties are exposed through the HttpRequest classes Browser property. Both WURFL capabilities and ASP.NET Browser properties can be used with the property attribute. If none of the <locations> match and the requesting device is a mobile device, then the mobileHomePageUrl will be used.

iii) Detector Module in web.config

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 Setting 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 Setting 4
 

 <!-- To avoid errors due to Code Access Security 
	(CAS) the web.config defaults to set trust level to full.-->
 <trust level="Full"> 
iii) Detector Module in global.asax

The latest version, 0.1.11.8, provides another method to intercept using .NET 4 and global.asax, allowing for a slight boost in performance and a more elegant web.config. To do this, the following code needs to be placed in global.asax:

Global.asax Setting
  #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
 }
 } 

To allow this to work properly, the modules section needs to be removed and the foundation.dll recompiled with the VER4 compiler signal. See below for where to obtain the source code.

Step 4: Download Mobile Emulators To Test Web site

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

Download Source Code

Download the source code for the sample application explained in Approach2.

Result

When the website is accessed from a mobile device, the user will be redirected to the appropriate mobile view. Unlike Approach 1, 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 be used for customization. It has simple access to the entire WURFL database that can be exposed in code, useful if you need to more advanced redirection that can utilize session variables or time of day or anything else that you need.

Accessing mobile capabilities
 string capability = Request.Browser["is_tablet"]; 

The entire list of WURFL capabilities can be found here.

Conclusion

If you’re developing mobile websites and struggling with the variety of mobile devices, use Approach 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.

Resources

  • Click here for more details on .NETMobile API.
  • Click here for detailed information on web.config settings for .NETMobile API usage.

History

  • 12th January, 2011: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Amimpat
Web Developer
India India
i am fine

Comments and Discussions

 
Questionredirecting mobile devices using database stored information Pinmemberlions18557-Oct-13 17:05 
Question51degree.mobi is free? PinmemberFarhan Ali2-Apr-13 1:44 
AnswerRe: 51degree.mobi is free? PinmemberKilla_BRE7-Jan-14 10:23 
QuestionMissing File Pinmemberolivia00727-Mar-12 2:23 
Where is App_Data/wurfl.xml.gz? App_Data folder contains only web_browsers_patch.xml file.
QuestionView Full Site link on the Mobile Site PinmemberDanLoffler5-Mar-12 6:15 
Generalhave 5 PinmemberPranay Rana12-Jan-11 9:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.141022.2 | Last Updated 12 Jan 2011
Article Copyright 2011 by Amimpat
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid