Detect Mobile Device using ASP.NET

Not many developer are aware that there is a property available in .NET called the HttpCapabilitiesBase.IsMobileDevice that lets you detect Mobile Device Browsers. Just use the following code:

C#

using System;
using System.Web;
using System.Web.Configuration;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpBrowserCapabilities hbc = Request.Browser;
if (((HttpCapabilitiesBase)hbc).IsMobileDevice)
{
Response.Write("You are browsing from a mobile device");
}
else
{
Response.Write("No mobile device");
}
}
}




VB.NET


Imports System
Imports System.Web
Imports System.Web.Configuration

Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim hbc As HttpBrowserCapabilities = Request.Browser
If (CType(hbc, HttpCapabilitiesBase)).IsMobileDevice Then
Response.Write("You are browsing from a mobile device")
Else
Response.Write("No mobile device")
End If
End Sub
End Class







About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

5 comments:

Anonymous said...

It does not works when testing in mobile emulators like opera.

Daniel K said...

Correct, you have to use *.browser files and determine additional items.
When I have the answer, I will update this site.

Suprotim Agarwal said...

Daniel is right. You can add additional browser capabilities using .browser file.

Try this url http://browsers.garykeith.com/downloads.asp

Btw, I somehow feel that the hbc object has the capabilities of the Opera10 browser. I am not sure where I read it.

Anonymous said...

Would it be possible to change the Response.Write to Response.Redirect to a lightweight mobile site? If so, would this be SEO friendly?

Cheers,

Michael

Patrick said...

try Response.RedirectPermanent("url")