Monday, March 9, 2015

Detecting Mobile Browsers using ASP.NET and C#

If you want to do server-side detection of Mobile Browsers in C#, surprisingly enough, it is not that easy!!

I thought that I could simply use the IsMobileDevice property from the HttpContext Request Browser object, but while this works for many mobile device browsers, it certainly does not work for all of them!

For example, I tried browsing to my website using the built-in mobile browser on my Samsung Android phone.

Sure enough, the mobile browser was detected and the web page informed me that my mobile browser was not supported.

However, I looked through my Visitor Stats on my site and I found that people had been install Mozilla Firefox for Android.  I tried installing this browser on my phone and sure enough, my web page did not detect the browser as a mobile browser!!

Fortunately, I found this site which provides a C# script which can be used in your ASP.NET/C# code to properly detect mobile browsers.  http://detectmobilebrowsers.com/

Since the code seemed a bit outdated, I updated the following line to match newer standards:

string u = HttpContext.Current.Request.UserAgent;

Once I updated my code to use the Regular Expression provided on this site, I was able to successfully detect the Mozilla Firefox for Android browser as a mobile browser and block it from being used on my site!




No comments:

Post a Comment