<

ASP.NET : Mobile Device Detection and Redirection

Published on
31,396 Points
24,696 Views
2 Endorsements
Last Modified:
Approved
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");
	}
}

Open 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.
 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>

Open 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> 

Open 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>

Open 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>

Open 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. 
	}
}

Open 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.

 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.
2
Comment
Author:amimpat
0 Comments

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Join & Write a Comment

See the Basics of Office 365's Note Taking app, OneNote
Check How effective MS Exchange Expert thinks Exchange Mailbox Recovery by SysTools IS. Visit the Official site to get detailed information:- https://www.systoolsgroup.com/exchange-recovery.html (https://www.systoolsgroup.com/exchange-recovery.h…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month