How to detect Mobile Handset,Browser Detection & Redirection in ASP.NET?


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.


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 mobiledevices 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 standardmobile theme URL.

ii) Mobile device database to fetch mobile capabilities in order to deliver the best possible experience tomobile 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 thePage_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"))
        	else if (userAgent.Contains("nokia"))      	

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 .NET Mobile API To Detect The User-Agent 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 BBCBank of AmericaMySpace andAdmob among others. WURFL device database is widely-accepted as the most advanced and up-to-date mobiledevice 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 updateweb.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: 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
    <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" 
	FiftyOne.Foundation" requirePermission="false" allowDefinition="Everywhere" 
	restartOnExternalChanges="false" allowExeDefinition="MachineToApplication"/>
      <section name="wurfl" 
	FiftyOne.Foundation" requirePermission="false" allowDefinition="Everywhere" 
	restartOnExternalChanges="false" allowExeDefinition="MachineToApplication"/>
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 mobiledevices.

Web.config Setting 2
    <!--<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
    mobilePagesRegex    A regular expression that when applied to the current request Path
                        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)
                        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.
      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. 

    <redirect firstRequestOnly="true"
        <!-- Don't redirect requests that have the noredirect query string parameter. -->
        <location url="">
          <add property="Url" matchExpression="[&|\?]noredirect"/>
        <!—- Send tablets to their own home page. -->
        <location url="~/Tablet/Default.aspx">
          <add property="is_tablet" matchExpression="true"/>
        <!—- Send iPhone to their own home page. -->
        <location url="~/Apple/Default.aspx">
          <add property="MobileDeviceManufacturer" matchExpression="Apple"/>

    <!--<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 
    newDevicesURL         provides a URL where new devices found on your server 
                          can be recorded
    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"
        <add capabilityName="pointing_method"/>
        <add name="browser_definitions"
               filePath="~/App_Data/web_browsers_patch.xml" enabled="true"/>

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.-->
    <add name="Detector" type="FiftyOne.Foundation.Mobile.Detection.DetectorModule, 
 <!-- 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.-->
      <remove name="Detector"/>
      <add name="Detector" type="FiftyOne.Foundation.Mobile.Detection.DetectorModule, 
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,, 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;

 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.
 OnPostAcquireRequestState(sender, e);

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.


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

How to Detect Client Browser in ASP.NET ?
protected void GetBrowserInfo()
System.Web.HttpBrowserCapabilities browser = Request.Browser;
string s = “Browser Capabilities\n”
+ “Type = ” + browser.Type + “\n”
+ “Name = ” + browser.Browser + “\n”
+ “Version = ” + browser.Version + “\n”
+ “Major Version = ” + browser.MajorVersion + “\n”
+ “Minor Version = ” + browser.MinorVersion + “\n”
+ “Platform = ” + browser.Platform + “\n”
+ “Is Beta = ” + browser.Beta + “\n”
+ “Is Crawler = ” + browser.Crawler + “\n”
+ “Is AOL = ” + browser.AOL + “\n”
+ “Is Win16 = ” + browser.Win16 + “\n”
+ “Is Win32 = ” + browser.Win32 + “\n”
+ “Supports Frames = ” + browser.Frames + “\n”
+ “Supports Tables = ” + browser.Tables + “\n”
+ “Supports Cookies = ” + browser.Cookies + “\n”
+ “Supports VBScript = ” + browser.VBScript + “\n”
+ “Supports JavaScript = ” +
browser.EcmaScriptVersion.ToString() + “\n”
+ “Supports Java Applets = ” + browser.JavaApplets + “\n”
+ “Supports ActiveX Controls = ” + browser.ActiveXControls
+ “\n”
+ “Supports JavaScript Version = ” +
browser[“JavaScriptVersion”] + “\n”;
Label1.Text =”Mr.SHEKHAR Says: Your Browser is :\n”+s;


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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s