Detecting request from mobile device

Take control over what is and what is not mobile device for your web app

Microsoft made is easy to detect whether request to your web application is coming from mobile device or not by adding a property to Request class. Usage of this is Request.Browser.IsMobileDevice.

This works pretty fine for most of mobile devices, but this property is based on list of mobile browsers which is configured in .NET framework itself.

Now-days, when mobile devices industry is growing, you might get wrong mobile device recognition by using this approach because of the simple reason and that is .NET framework configuration is not updating automatically when mobile device platform is published.

You can always update definition file, but you will need to have full access to your server machine, so this will not work if you are using shared host.

Note

Browser definition files are stored in folder C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\Browsers

What you can do is to extend Request class with another method which will check UserAgent name. Keywords of UserAgent names for mobile browsers you can store in web.config as a comma separated value.

<appSettings>
	<add key="mobileBrowsers" value="Blackberry,BB10,iPad,iPhone,Windows Phone,Windows CE"/>
</appSettings>
    

Create extension method for Request which compares this list of values with request user agent name.

public static bool IsMobile(this HttpRequest request)
{
foreach (string mobileBrowser in System.Web.Configuration.WebConfigurationManager.AppSettings["mobileBrowsers"].Split(','))
{
if (request.UserAgent.ToLower().Contains(mobileBrowser.Trim().ToLower()))
{
return true;
}
}
return false;
}

After including namespace in which this extension is declared you can easily check whether page is accessed from mobile device with  Request.IsMobile().

If new device or platform with specific signature keyword, you can easily add and enable your website to recognize it.

References

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article