ASP.NET : Mobile Device Detection and Redirection

AID: 2298
  • Status: Published

5850 points

  • Byamimpat
  • TypeTutorial
  • Posted on2010-01-19 at 22:55:46
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.

Examples in below article are in c#.net

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");
	}
}
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

Select allOpen in new window



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 need to install these templates as they are already installed.

1. Create a C# ASP.NET website.
2. The website will be created with a default web form "Default.aspx", keep the name as it is.
3. 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

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.gz
- bin/Mobile.dll

These files can be extracted from the Enhance download that is started automatically by clicking the link under Step 1  on this page.  

Once downloaded your website should have following folder structure.
 
folderstruct.jpg
  • 14 KB
  • FolderStructure
FolderStructure


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 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>
                                    
1:
2:
3:
4:
5:
6:

Select allOpen in new window



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="Debug"/>
            <!-- 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> 
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

Select allOpen in new window



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

Select allOpen in new window



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>
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:

Select allOpen in new window



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. 
	}
}
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:

Select allOpen in new window



Step5: Build 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 be used for customization.

 
mobview1.jpg
  • 19 KB
  • Mobile Output
Mobile Output


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

Conclusion:
If you’re developing mobile websites and struggling with the variety of mobile devices use Method2 as explained above.  It will reduce development time, use device data you can trust and leave you free to focus on delivering an amazing mobile experience.

Resource:
i) Click here for more details on .NETMobile API.
ii) Click here for detailed information on web.config settings for .NETMobile API usage.
    Asked On
    2010-01-19 at 22:55:46ID2298
    Tags

    ASP.NET

    ,

    Device Detection

    ,

    Browser Detection

    ,

    ASP.NET Mobile

    ,

    Mobile Web

    Topic

    Programming for ASP.NET

    Views
    11443

    Comments

    Add your Comment

    Please Sign up or Log in to comment on this article.

    Join Experts Exchange Today

    Gain Access to all our Tech Resources

    Get personalized answers

    Ask unlimited questions

    Access Proven Solutions

    Search 3.2 million solutions

    Read In-Depth How-To Guides

    1000+ articles, demos, & tips

    Watch Step by Step Tutorials

    Learn direct from top tech pros

    And Much More!

    Your complete tech resource

    See Plans and Pricing

    30-day free trial. Register in 60 seconds.

    Loading Advertisement...

    Top ASP.NET Experts

    1. CodeCruiser

      420,756

      Wizard

      2,010 points yesterday

      Profile
      Rank: Genius
    2. kaufmed

      283,163

      Guru

      500 points yesterday

      Profile
      Rank: Genius
    3. BuggyCoder

      269,283

      Guru

      3,600 points yesterday

      Profile
      Rank: Sage
    4. tommyBoy

      171,028

      Guru

      0 points yesterday

      Profile
      Rank: Genius
    5. TheLearnedOne

      165,990

      Guru

      0 points yesterday

      Profile
      Rank: Savant
    6. ddayx10

      139,847

      Master

      0 points yesterday

      Profile
      Rank: Sage
    7. MlandaT

      122,463

      Master

      0 points yesterday

      Profile
      Rank: Genius
    8. techChallenger1

      107,384

      Master

      0 points yesterday

      Profile
      Rank: Guru
    9. navneethegde

      90,197

      Master

      0 points yesterday

      Profile
      Rank: Wizard
    10. Masteraco

      82,909

      Master

      0 points yesterday

      Profile
      Rank: Wizard
    11. Dhaest

      80,693

      Master

      2,000 points yesterday

      Profile
      Rank: Genius
    12. vs00saini

      76,565

      Master

      0 points yesterday

      Profile
      Rank: Wizard
    13. Chinmay_Patel

      73,407

      Master

      0 points yesterday

      Profile
      Rank: Genius
    14. stephanonline

      69,461

      Master

      0 points yesterday

      Profile
      Rank: Wizard
    15. nishantcomp2512

      68,521

      Master

      0 points yesterday

      Profile
      Rank: Wizard
    16. srosebabu

      67,676

      Master

      0 points yesterday

      Profile
      Rank: Guru
    17. markmiddlemist

      65,828

      Master

      0 points yesterday

      Profile
      Rank: Master
    18. jacko72

      65,660

      Master

      0 points yesterday

      Profile
      Rank: Genius
    19. sammySeltzer

      64,318

      Master

      0 points yesterday

      Profile
      Rank: Genius
    20. wdosanjos

      59,639

      Master

      0 points yesterday

      Profile
      Rank: Genius
    21. mroonal

      58,080

      Master

      0 points yesterday

      Profile
      Rank: Sage
    22. mas_oz2003

      56,140

      Master

      0 points yesterday

      Profile
      Rank: Genius
    23. Rouchie

      55,801

      Master

      0 points yesterday

      Profile
      Rank: Genius
    24. Lalit-Chandra

      54,514

      Master

      0 points yesterday

      Profile
      Rank: Master
    25. EaswaranP

      54,203

      Master

      0 points yesterday

      Profile
      Rank: Guru

    Hall Of Fame