Wednesday, March 6, 2013

Server-side mobile device check


Problem:
When we want to display information conditionally according to end devices used, we may use CSS Media Queries. However, they do not prevent additional overhead from rendering server-side controls.

Solution:
Use server side checks, either to the growing unsupported Request.Browser.IsMobileDevice property, or by check the User Agent for specific sets of strings.


public static bool IsMobileDevice(HttpRequest request)
        {
            try
            {
                //IsMobileDevice property
                if (request.Browser.IsMobileDevice)
                {
                    return true;
                }

                //user agent check
                var useragent = request.UserAgent;

                string[] stringArray = { "android", "ipad", "iphone", "ipod" };
                if(useragent != null)
                {
                    if (stringArray.Any(s => useragent.ToLower().Contains(s)))
                    {
                        return true;
                    }
                }

                //fallback
                return false;
            }
            catch
            {
                return false;
            }
        }

Sources:
http://dbarrowstechblog.blogspot.pt/2011/02/requestbrowserismobiledevice.html
http://www.codeproject.com/Articles/34422/Detecting-a-mobile-browser-in-ASP-NET?msg=4189784#xx4189784xx
http://stackoverflow.com/questions/5341637/how-do-detect-android-tablets-in-general-useragent

Other, more relyable methods:
http://wurfl.sourceforge.net/
http://51degrees.codeplex.com/

Update:
- To exclude tablets from the listing, remove "ipad" and "android" and add "mobile". Since android phones contain the "mobile" keyword and android tablets do not, that will be enough.

No comments:

Post a Comment