by Joakim

Detecting Browser Types and Browser Capabilities in Asp.Net

The following helper class allows you to detect browser types and browser capabilities in Asp.Net. It works in both MVC-controllers/views and WebAPI-controllers (and I would think it should work with WebForms as well).

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Web;
using System.Web.Configuration;

namespace MyProject.Helpers
{
    public static class BrowserInfoHelper
    {
        public static string GetUserAgent()
        {
            return HttpContext.Current.Request.UserAgent;
        }

        public static HttpBrowserCapabilities GetCapabilities()
        {
            var capabilities = new HttpBrowserCapabilities();

            var hashtable = new Hashtable(180, StringComparer.OrdinalIgnoreCase);
            hashtable[string.Empty] = GetUserAgent();
            capabilities.Capabilities = hashtable;

            var capabilitiesFactory = new BrowserCapabilitiesFactory();
            var headers = new NameValueCollection();
            capabilitiesFactory.ConfigureBrowserCapabilities(headers, capabilities);
            capabilitiesFactory.ConfigureCustomCapabilities(headers, capabilities);

            return capabilities;
        }
    }
}

 

Then use it, for example in an MVC-view, like so;

@MyProject.Helpers
@{
    var browserCapabilities = BrowserInfoHelper.GetCapabilities();
    var browserIsOldIE = browserCapabilities.Browser.Equals("IE", StringComparison.InvariantCultureIgnoreCase) && browserCapabilities.MajorVersion < 9;
}
@if (browserIsOldIE)
{
    <div>Please upgrade your browser!</div>
}