Mobile Web Browser Detection and Redirection in C# for ASP.net

by Chris Sunday, July 19 2009
UPDATE: We have recently changed the code which we use on our website. It is a little cleaner and more complete. To see the newest version, check out our latest post on mobile web browser detection and redirection in C-Sharp (C#) for ASP.net.

If you wish, however, you can still use the code on this page, which will work just fine.

Adding server-side browser detection and redirection to your website using the ASP.net platform and C# (C-Sharp) is actually quite easy. Below, you will see the code which we have implemented on our site. Though it may not catch ALL browsers (because there are a heck of a lot of them), it will catch most.

This code should be inserted into the Page_Load event of the codebehind file (e.g., samplepage.aspx.cs). To enable this site-wide, just add it to the Page_Load event of the Master Page file.

if (Request.Headers["User-Agent"] != null && (Request.Browser["IsMobileDevice"] == "true" || Request.Browser["BlackBerry"] == "true" || Request.UserAgent.ToUpper().Contains("MIDP") || Request.UserAgent.ToUpper().Contains("CLDC")) || Request.UserAgent.ToLower().Contains("iphone"))
{
Response.Redirect("http://mobile.abwebsitedesign.com");
}


The preceding code will allow you to add as many User Agents as you wish by just adding additional Request.UserAgent properties. The else statement is not necessary in this case, because we want the page to load normally, unless the UserAgent is not a standard browser.

If you wanted to redirect to a certain page for either case, you can do something similar to the following as well:

if (Request.Headers["User-Agent"] != null && (Request.Browser["IsMobileDevice"] == "true" || Request.Browser["BlackBerry"] == "true" || Request.UserAgent.ToUpper().Contains("MIDP") || Request.UserAgent.ToUpper().Contains("CLDC")) || Request.UserAgent.ToLower().Contains("iphone"))
{
Response.Redirect("http://www.abwebsitedesign.com/mobile.html");
}
else
{
Response.Redirect("http://www.abwebsitedesign.com/standard.aspx");
}


Tags: , , , ,

ASP.net | Microsoft

Comments

10/16/2009 2:37:40 AM #

evan

Great resource!! Thank you for sharing this info!

evan United States | Reply

3/24/2010 12:02:20 PM #

Autumn

Can you give example code of Page_Load event of the codebehind file?

Autumn United States | Reply

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



About this Blog

This is a blog about web design and all things that are related to web design. Pertinent and relevant comments and/or questions are highly encouraged, but please be courteous and thoughtful of others whilest making comments.

If you have benefited from a post, please do the right thing and promote it. You can do this by linking to it, tweeting it, or digging it.

Thank you much.

Recent Comments

Comment RSS