How to Detect Mobile Device Request in Asp.net

In aps.net we can easily detect that client is mobile device browser using HttpCapabilitiesBase class. This class provides several methods to detect different properties of client web browser. This class has one property IsMobileDevice which tell client is mobile or not. It returns true if the browser is a recognized mobile device.

Example to detect mobile device

public static bool IsMobile
{
get
{
System.Web.HttpBrowserCapabilities myBrowserCaps = HttpContext.Current.Request.Browser;
if (((System.Web.Configuration.HttpCapabilitiesBase)myBrowserCaps).IsMobileDevice)
{
return true;
}
else
{
return false;
}
}
}

In above example I used current request Browser property which returns HttpBrowserCapabilities object. Just put this property in and util class and use it.

For more better result we can use our detection along with above by matching user agents.

private static readonly Regex RegexMobile =
new Regex(
@"(iemobile|iphone|ipod|android|nokia|sonyericsson|blackberry|samsung|sec-|windows ce|motorola|mot-|up.b|midp-)",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
public static bool IsMobile
{
get
{
var context = HttpContext.Current;
if (context != null)
{
var request = context.Request;
if (request.Browser.IsMobileDevice)
{
return true;
}
if (!string.IsNullOrEmpty(request.UserAgent) && RegexMobile.IsMatch(request.UserAgent))
{
return true;
}
}
return false;
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *