a web design blog.

Tuesday, September 2, 2008

Mobile Web Browser Detection and Redirection in C# for ASP.net (server-side)

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");
}

Labels: , ,