ASP.NET Mobile Detection

ASP.NET provides one way of detecting mobile devices through Request.Browser.IsMobileDevice, however that does not always work with newer browsers and smartphones. Considering smartphone use is on the rise, many websites are now also available for mobile devices. In the below example we can detect a mobile device, however it will not detect every device. We will also add a link to the desktop site, which will work via a cookie. For a more robust mobile detection it is recommended you look at the 51degrees.mobi.

C# Code

string strUserAgent = Request.UserAgent.ToString().ToLower();
bool MobileDevice = Request.Browser.IsMobileDevice;
if(Request.Cookies["MobileDevice"] != null){if (Request.Cookies["MobileDevice"].Value == "IgnoreMobile" ){MobileDevice = false;}
   } else {
if (strUserAgent != null){
if (MobileDevice == true ||strUserAgent.Contains("iphone") ||strUserAgent.Contains("blackberry") ||strUserAgent.Contains("mobile") ||
strUserAgent.Contains("android") ||strUserAgent.Contains("windows ce") ||strUserAgent.Contains("opera mini") ||strUserAgent.Contains("palm"))
{
  Response.Redirect("http://m.thecodingguys.net");
}
   }
  }

The browser (user-agent) is detected and if it contains anything such as Android or iPhone, it will redirect to the subdomain m.thecodingguys.net. However, if a cookie called MobileDevice exists in the user’s browser, the redirect will not happen.The problem with this browser detection script is that since new mobile phones come out every day, you will probably need to update it regularly and add those phones in.

Now in your website root directory (or wherever you prefer) make a new file called IgnoreMobile.aspx or IgnoreMobile.cshtml, and then add the following code:

Response.Cookies["MobileDevice"].Value = "IgnoreMobile";
Response.Cookies["MobileDevice"].Expires = DateTime.Now.AddDays(30);
Response.Redirect("~/Default.cshtml");

This code creates a cookie in the user’s browser called MobileDevice with the value IgnoreMobileDevice, and the second line tells the cookie when to expire (30 days from the day it was inserted into the browser). Then the user is redirected back to the main page.

Only the domain which inserts the cookie can read the cookie!

In your mobile site footer and the link to your desktop site, the URL should be http://example.com/IgnoreMobileDevice.aspx (or cshtml). This will quickly insert the cookie and redirect the user to the main page; the main page will read the cookie and will not redirect.

Some mobiles don’t support cookies or some users are not accepting cookies, so this may not always work.