September 27, 2010

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




'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

5 Responses to "Detect Mobile Device using ASP.NET"
  1. Anonymous said...
    September 28, 2010 11:39 PM

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

  2. Daniel K said...
    September 30, 2010 8:35 AM

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

  3. Suprotim Agarwal said...
    September 30, 2010 9:40 AM

    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.

  4. Anonymous said...
    October 2, 2010 11:13 PM

    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

  5. Patrick said...
    October 3, 2010 7:55 PM

    try Response.RedirectPermanent("url")

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions