I’ve been thinking about supporting mobile devices on this website for a while now. It’s not that the website doesn’t work on mobile devices, but the whole experience could be more optimized for phones and PDA’s. The weight of the HTML and CSS had to be reduced and I thought a simpler interface would improve the readability.

The plan was to auto-discover when a mobile client accessed the site and then apply the mobile theme at runtime. To determine if the client was a mobile device I used the Request.Browser.IsMobileDevice property, but then I realized that it isn’t bullet proof. New devices and manufacturers are popping up all the time and the .NET Framework is relatively old in that regard.

So, instead I used a combination of the Request.Browser.IsMobileDevice property and a custom regular expression lookup.

The code

First of all, I used a very simple regular expression and added it to the appSettings in the web.config.

<add key="MobileDevices" value="(nokia|sonyericsson|blackberry|samsung|sec-|windows ce|motorola|mot-|up.b)" />

Then I wrote a property called IsMobile which tries the Request.Browser.IsMobileDevice property first, and then tries the regular expression afterwards.

private static readonly Regex MOBILE_REGEX = new Regex(ConfigurationManager.AppSettings.Get("MobileDevices"), RegexOptions.IgnoreCase | RegexOptions.Compiled);


public static bool IsMobile




    HttpContext context = HttpContext.Current;

    if (context != null)


      HttpRequest request = context.Request;

      if (request.Browser.IsMobileDevice)

        return true;


      if (!string.IsNullOrEmpty(request.UserAgent) && MOBILE_REGEX.IsMatch(request.UserAgent))

        return true;



    return false;



The reason I didn’t use some of the web.config features such as browserCaps is because then the web.config would be filled with browser related markup. There is nothing wrong with that, but I like to keep the web.config as clean as possible.

With this method it is now easy to apply a special mobile theme for mobile clients only. You can test it out by visiting this website using your phone or PDA or force the theme.


Comments are closed