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:


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");
Response.Write("No mobile device");


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")
Response.Write("No mobile device")
End If
End Sub
End Class

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal


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

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?



Patrick said...

try Response.RedirectPermanent("url")