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.
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
- http://stackoverflow.com/questions/1829089/how-does-ismobiledevice-work
- http://forums.asp.net/t/1924596.aspx?IE+11+Request+Browser+isMobileDevice+property+returning+TRUE+in+Browsers
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.
Comments for this article