Mobile Device Detection in C#

In the modern world of MVC, responsive design, and everything that surrounds the modern era of Web development, you may be forgiven for believing that you no longer have to detect the mobile devices coming to your site. You should just be able to craft your UI to “adapt” and let the browser and the device take care of the rest, right?

In an ideal world, the answer to that would be a resounding yes, but we don’t live in an ideal world, so often the answer will be no. In some cases, it is still an advantage to attempt to detect the device connecting to your site and decide to give a different user experience based on those decisions.

Fortunately, ASP.NET has your back covered here. For a long time, ASP.NET has had the ability built in to determine all sorts of interesting things from the incoming connection, one of which is a simple flag telling you if the browsing client is a mobile device or not.

For this post, create yourself a new ASP.NET Web application in Visual Studio. You can use the pre-made templates if you want, but I’ll be creating a blank project and just adding pages as I need them.

For me, my project template looks like this:

Mobile1
Figure 1: Choose an ASP.NET web application

And, in the next dialog:

Mobile2
Figure 2: Empty Web app with Web forms added

A little bit of a disclaimer here: I’ve not tested this in ASP.NET MVC but, because the request pipeline is mostly the same, the same properties should be available. If you do confirm it, please let me know in the comments.

Once you have a new project up and running, add a new Web forms page and make sure that the HTML for it looks like the following:

<%@ Page Language="C#"
    AutoEventWireup="true"
    CodeBehind="Index.aspx.cs"
    Inherits="DeviceDetection.Index" %>

<!DOCTYPE html>

<html >
<head runat="server">
   <title>Device Detection Sample</title>
</head>
<body>
   <form id="form1" runat="server">
   <div>

      <h1>Device Detection</h1>
      <p>The label below will be updated to tell you
         if you're on a mobile device or not:</p>
      <asp:label runat="server"
         id="txtMobiDevice"></asp:label>

   </div>
   </form>
</body>
</html>

Remember, if you’ve called your project by a different name or namespace, DON’T replace the <%@ …. %> first line; leave that as it is and just replace everything below it.

Your code behind file for the ASPX should look something like the following:

using System;

namespace DeviceDetection
{
   public partial class Index : System.Web.UI.Page
   {
      protected void Page_Load(object sender, EventArgs e)
      {
         if(Request.Browser.IsMobileDevice)
         {
            txtMobiDevice.Text = "You're using a
               mobile device";
         }
         else
         {
            txtMobiDevice.Text = "You're NOT using a
               mobile device";
         }
      }


   }
}

That simple bit of code allows you to tell if you’re browsing from a browser:

Mobile3
Figure 3: The result of browsing from Chrome on the PC

Or, if you’re browsing from your device:

Mobile4
Figure 4: The same page browsed to using Pocket Internet Explorer and Opera Mobile from my HTC phone via Pocket Controller

Detecting a Mobile Device Is Great, but We Can Do More

With the various toolkits that are about, we actually can get even more details.

For a long time now, the folks that run the “wurfl” project have been collecting ad collating data for just about every mobile device ever invented. You can find out about the project at http://wurfl.sourceforge.net/.

They provide a free to use data set that contains things like screen width, screen height, bit depth, and number of colours, as well as many other things like the types of media the device supports and lot’s more.

Unfortunately, it’s a little bit of a headache to dig through the data and make sense of it, so the good people at “51degrees” have made a project available both on Codeplex and as a NuGet package.

Add the package to your Web application created just a moment ago, by firing up your NuGet package manager and looking for “51Degrees.mobi”, as shown in Figure 5.

Mobile5
Figure 5: 51 Degrees mobile detection package on NuGet

Once this has been added, you then can use the extra functionality available in your code.

Change your index.aspx page so that it looks as follows. (Remember, don’t change the first line if you use different name spaces.)

<%@ Page Language="C#" AutoEventWireup="true"
   CodeBehind="Index.aspx.cs"
   Inherits="DeviceDetection.Index" %>

<!DOCTYPE html>

<html >
<head runat="server">
   <title>Device Detection Sample</title>
</head>
<body>
   <form id="form1" runat="server">
   <div>

      <h1>Device Detection</h1>
      Mobile Device: <asp:label runat="server"
         id="txtMobiDevice"></asp:label><br/>
      Browser Name: <asp:label runat="server"
         id="txtBrowserName"></asp:label><br/>
      Browser Version: <asp:label runat="server"
         id="txtBrowserVersion"></asp:label>

   </div>
   </form>
</body>
</html>

Make sure you have the following in your code behind:

protected void Page_Load(object sender,
   EventArgs e)
{
   txtMobiDevice.Text =
      Convert.ToBoolean(Request.Browser["IsMobile"]) == true) ?
      "Yes" : "No";
   txtBrowserName.Text =
      Request.Browser["BrowserName"];
   txtBrowserVersion.Text =
      Request.Browser["BrowserVersion"];
}

If you run this in your PC’s Web browser, you’ll see the following:

Mobile6
Figure 6: The new detector in the PC browser

In my case, I’m running using Chrome V45.

If I once again point my mobile at the page:

Mobile7
Figure 7: Our site viewed from a mobile device

You’ll immediately see that we get an altogether different page. That’s because, by default, 51 degrees automatically wires things up to redirect you to a different site located in the “Mobile” folder that it creates in your solution when you install it.

The test page in the mobile site allows you to see the immense range of property values the toolkit can detect. You may have also noticed that some of the properties are marked “Upgrade.” This is because 51 degrees also make available a commercial toolkit that reveals much more data about the target device that, in the free version, is not available. By using the various properties and options available, you now can not only adapt your site but make be 100% aware of exactly what devices can do what, too.

.NET got you some .NOT? Drop me a comment below and maybe I can help figure out how to turn that .NOT in to a .YEA and find a .NET way of doing things.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read