Click here to Skip to main content
Click here to Skip to main content

How to Detect Browser Capabilities in ASP.NET

By , 21 Sep 2012
 

Introduction 

Proper detection of Web Browsers' type and capabilities is rather important from both end-user's and developer's perspectives. The differences between Web Browsers, rooted in either branding or versioning, could cause serious portability issues, potentially resulting in some Web applications rendering incorrectly, or even not running at all.  Hopefully, strict adherence to emerging HTML5/CSS3 specs will help to dramatically improve inter-browsers compatibility and, correspondingly, the portability of Web apps.

Solution

A simple browser-detection feature could be added to ASP.NET web applications providing valuable feedback to end users and also helping the tech support folks to perform remote troubleshooting based on the clients' input regarding the web browser(s) in use.

Demo

A working DEMO is available at www.webinfocentral.com (click on the button “Browser”). A sample screenshot is shown below in Fig.1:

Figure 1. Sample screenshot demonstrating browser capabilities

Background 

This project demonstrates a simple implementation of server-side browser type/capabilities detection feature, written in C# with just a little bit of client-side Java scripting added for better responsiveness and interactivity. The same or even better level of responsiveness/interactivity could be achieved by using either ASP.NET AJAX or Microsoft Silverlight™ RIA technology set instead of JavaScript.

Code 

The project code written in C# compatible with any ASP.NET 2.0+ web site contains the following:

  • Class Module "BrowserInfo.cs" to be placed in AppCode directory
  • Default Web page "Default.aspx" to be placed in Application root directory

The core functionality is encapsulated in the class module "BrowserInfo.cs" shown below (notice some optional extensions, commented-off in the code; also, for simplicity and readability this solution is using simple string concatenation. Some performance improvement could be achieved by implementing StringBuilder object for string manipulation):

//******************************************************************************
// Module           :   BrowserInfo.cs
// Author           :   Alexander Bell
// Copyright        :   2008-2009 Infosoft International Inc
// Date Created     :   01/15/2008
// Last Modified    :   09/14/2009
// Description      :   Get Browser info
//******************************************************************************
// DISCLAIMER: This Application is provide on AS IS basis without any warranty
//******************************************************************************
using System;
using System.Web;
///*****************************************************************************
/// <summary>Server sider Browser detection: ASP.NET 2.0</summary> 
public static class InfosoftBrowserInfo
{
    #region Get Browser capabilities
    /// <summary>Browser capabilities: 2D array of Name/Values</summary>
    public static string[,] BrowserAttributes
    {
        get
        {
            string _agent = String.Empty;
            if (HttpContext.Current == null) return null;
            try
            {
                // detailed string describing some of browser capabilities
                _agent = HttpContext.Current.Request.UserAgent;
                // browser capabilities object
                HttpBrowserCapabilities _browser = HttpContext.Current.Request.Browser;
                // browser capabilities (properties) 2D array of strings, Name/Value
                string[,] arrFieldValue = 
                {
                    {
                    //"Type",
                    "Name",
                    "Version",
                    //"Major Version",
                    //"Minor Version",
                    "Platform",
                    "ECMA Script Version",
                    "Is Mobile Device",
                    "Is Beta",
                    //"Is Crawler",
                    //"Is AOL",
                    "Is Win16",
                    "Is Win32",
                    "Supports Frames",
                    "Supports Tables",
                    "Supports Cookies",
                    "Supports CSS",
                    "Supports VB Script",
                    "Supports JavaScript",
                    "Supports Java Applets",
                    "Supports ActiveX Controls",
                    "Supports CallBack",
                    "Supports XMLHttp",
                    
                    String.Empty,
                    "User Agent Details"
                    }, 
                    {
                    //_browser.Type,
                    
                    (_agent.ToLower().Contains("chrome"))? "Chrome" :_browser.Browser,
                    (_agent.ToLower().Contains("chrome"))? 
			"See User Agent Details below" :_browser.Version,
                    
                    //_browser.MajorVersion.ToString(),
                    //_browser.MinorVersion.ToString(),
                    
                    _browser.Platform,
                    _browser.EcmaScriptVersion.ToString(),
                    
                    (_browser.IsMobileDevice)? "YES": "NO",
                    (_browser.Beta)? "YES": "NO",
                    
                    //_browser.Crawler.ToString(),
                    //_browser.AOL.ToString(),
                    (_browser.Win16)? "YES": "NO",
                    (_browser.Win32)? "YES": "NO",
                    
                    (_browser.Frames)? "YES": "NO",
                    (_browser.Tables)? "YES": "NO",
                    (_browser.Cookies)? "YES": "NO",
                    (_browser.SupportsCss)? "YES": "NO",
                    (_browser.VBScript)? "YES": "NO",
                    (_browser.JavaScript)? "YES": "NO",
                    (_browser.JavaApplets)? "YES": "NO",
                    (_browser.ActiveXControls)? "YES": "NO",
                    (_browser.SupportsCallback)? "YES": "NO",
                    (_browser.SupportsXmlHttp)? "YES": "NO",
                    String.Empty,
                    _agent
                    }
                };
                return arrFieldValue;
            }
            catch { return null; }
        }
    }
    /// <summary>JavaScript string to containing Browsers capabilities</summary>
    public static string BrowserJavaScript
    {
        get
        {
            // return string contains JavaScript
            string MsgBrowser = String.Empty;
            string[,] arrBrowser = BrowserAttributes;
            if (arrBrowser == null) return String.Empty;
            try
            {
                // pop-up message using JavaScript:alert function
                MsgBrowser = "javascript:alert('Your Browser properties: \\n";
                for (int i = 0; i < arrBrowser.GetLength(1); i++)
                { MsgBrowser += "\\n" + arrBrowser[0, i] + " : " + arrBrowser[1, i]; }
                return MsgBrowser += "')";
            }
            catch { return String.Empty; }
        }
    }
    #endregion
}

A Sample Web Page contains a single Button1 control with "onclick" event handler added as shown below:

 <%@ Page Language="C#" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Browser Detection } Infosoft International Inc</title>
    
    <script runat="server">
        private string _browser;
        protected void Page_PreInit(object sender, EventArgs e)
        {_browser = InfosoftBrowserInfo.BrowserJavaScript;}
        protected void Page_Load(object sender, EventArgs e)
        { Button1.Attributes.Add("onclick", _browser);}
    </script>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Get Browser Info" />
        <br />
    </div>
    </form>
</body>
</html>

Points of Interest 

The solution is tested for compatibility with four major Web browsers:

  • Microsoft Internet Explorer 7.0+
  • Mozilla Firefox
  • Google Chrome
  • Apple Safari  

History

  • Article posted on 09/14/2009
  • Updated on 9/21/2012 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

DrABELL
Chief Technology Officer Infosoft Int'l
United States United States
Member
Dr. A. Bell has 20+ years of SW/EE experience, published 200+ tech articles and authored 37 inventions; Win/Web veteran, currently focused on: HTML5, CSS3, Javascript, jQuery, SQL, Windows 8, .NET, C#, WPF, Ultrabooks, Mobile. Developed popular Silverlight Media Player, 3 Fractions Calculator and best YouTube API for ASP.NET (#1 Goog). Sample pubs/projects:
  1. HTML5 Best Practices: Table formatting via CSS3
  2. Personal computer 2012
  3. New iPad: notes from NY Apple store
  4. YouTube and Facebook popularity metrics
  5. Edumatter M12: School Math Calculators and Equation Solvers
  6. How to select web browser and check its capabilities
  7. SQL generates large data sequence
  8. Aggregate Product function extends SQL
  9. Top-50 Digital Cameras
  10. Evolution of digital cameras
  11. WebTV Project: Embedded YouTube Player

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1memberPete Appleton25 Sep '12 - 0:11 
Article is based on user agent, and it's well known that using the user agent string for capability detection is poor practice because it's trivially set by the end-user. If you want to detect browser _capability_ as opposed to what it claims to be then you need to start running client-side code to actually check the capabilities then return the results to the server; for example, you could use the Modernizr library then parcel up the capability detection results in some serialised format and return it to the server.
GeneralRe: My vote of 1memberDrABELL25 Sep '12 - 2:52 
Hi Pete,
I totally disagree with your highly-opinionated judgement. Proposed solution may be not perfect (and none is), but still very practical, based on standard objects included in .NET library and used by programmers for many years. Your alternative suggestion might be considered just as a complementary, but not a primary one just for a simple reason that scripting may be disabled on client's machine, thus making your suggestion/solution totally useless. In addition to this, I would like to ask you to provide the link to any practical implementation of you solution online, so we would be able to compare results. It would be even better if instead of such unfair criticism you will provide us with your own alternative version in order to demonstrate the real advantages of your approach. Thanks.
GeneralRe: My vote of 1memberPete Appleton27 Sep '12 - 23:08 
Not a full explanatory article, but you might find this link relevant: http://msdn.microsoft.com/en-us/library/ie/hh273397(v=vs.85).aspx[^]. It's a little rare that my opinions are in step with Microsoft, but in this case it seems to be the case. As an aside, the fact that browser sniffing was used for many years is not a justification for continuing to do so; many other things such as control flow via GOTO and self-modifying code were done for many years until a better approach emerged, but we wouldn't consider those techniques now without a very strong imperative. If javascript is disabled on the client's machine - well, none of the stuff we do will work without it anyway as the UI is pretty much pure JS + HTML templates populated via AJAX, so I'm quite happy for the (client-side) "Javascript is disabled, turn it on or use a better browser" error to handle it.
--
What's a signature?

QuestionLimited by HttpContext.Current.Request.BrowseradminChris Maunder21 Sep '12 - 11:17 
Since this uses the inbuilt HttpContext.Current.Request.Browser object, it;s usefulness is limited to the accuracy of your .browser files - meaning not very accurate or useful.
 
I've already done a writeup of this at Browser Detection using ASP.NET[^]
cheers,
Chris Maunder
 
The Code Project | Co-founder
Microsoft C++ MVP

AnswerRe: Limited by HttpContext.Current.Request.BrowsermemberDrABELL21 Sep '12 - 12:32 
Hi Chris,
Thanks a bunch for your input. Btw, it actually has an option of using both:
HttpContext.Current.Request.UserAgent
and
HttpContext.Current.Request.Browser
I would agree that solution is not perfect, though still useful on many IRL biz occasions. As I am always eager to learn something new/useful/practical, thus will be glad to see a working demo of other browser detecting solutions and to compare results.
Have a great evening/weekend,
Alex
GeneralShort URLmemberDrABELL3 Jan '11 - 6:13 
How to select web browser and check its capabilities: http://exm.nr/BROWSE[^]
GeneralBrowser capabilities for MobilememberAmaresh Jois27 Aug '10 - 4:29 
Adding on to the above, the latest mobile capabilities list which is available in WURFL is read using 51degrees.mobi Foundation API which detects all mobile devices. It is a .NET open source available here http://51degrees.codeplex.com/releases which is very helpful for Mobile detection.
 
There is a 4 minute video on the usage of the toolkit to Enhance your existing website to contain mobile pages.
Video (3:43 minutes): http://www.youtube.com/watch?v=b4io5KB4Qt0
GeneralOr you can just use my page, and know even more about the browser....memberzachgotnosauce11 Jan '10 - 8:38 
We've added support for a lot of mobile devices, such as Android, iPhone, etc. This is a support page for the mobile site of BlogTalkRadio.
 
So we support a lot of stuff, partly b/c when a major platform comes out, we try to cover it adequately. We want to know things like mobile screen size (if we can), audio playback protocols and format, and so on.
 
If you find that we know something about a device you don't, feel free to email me and I'll supply you the .browser config file you need. Also, if you are seeing that we don't, feel free to contribute!
 

http://m.blogtalkradio.com/browser.aspx?show=y[^]
 
Thanks,
 
Zach Baker
www.blogtalkradio.com
General[Message Deleted]memberShadowX18 Sep '09 - 3:15 

General[My vote of 1] vote 1membermambo_215 Sep '09 - 4:04 
Hi Alex,
 
http://msdn.microsoft.com/en-us/library/system.web.httpbrowsercapabilities_members.aspx
 
This article is just about iteration over members of HttpBrowserCapabilities class and calling ‘alert’ function in JavaScript.
 
PS: Don't be disappointed Alex. If you write a really good article then I give you 5.
GeneralRe: [My vote of 1] vote 1 RE: you seem to be biased and unfair [modified]memberDrABELL15 Sep '09 - 4:52 
Dear faceless mambo_2
(sorry, this is just an observation made when checking your profile... no photo... btw, what are you actually hiding from people? and what happened to mambo_1? big smile... Smile | :)
 
I seriously doubt your ability to be objective in my case. It's already a second time you have posted very judgmental and opinionated comments to my articles; in your first post, in addition to pretty much baseless criticism of my work, you also start questioning the objectivity of other members, whose opinions were very different from yours. Pretty much looks like you have your own agenda here...
 
Second. From mambo_2 profile: Articles submitted - 0. Wow! Very impressive! Probably you should lead by example and show us couple+ of your own "good articles" as mentioned in your super-critical post?
 
Well, I spent too much time already commenting on your comments. I am giving your firm 1 (though it should be 0 to match the number of your "good articles" posted Smile | :) It would be much more productive approach than just trashing the works of others based on your rather subjective likes and dislikes...
 
Wrapping it up quickly: Don't be dissapointed, mambo_2. Smile | :) Just try to post couple good articles of your own... and learn to be more tolerant to other members' work and opinions.
 
Bye.
 
PS. ... and in response to your PS: if you write a "really good article" then I will give you 5.0... instead of just 0 as of now Smile | :)
 
modified on Tuesday, September 15, 2009 11:00 AM

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 21 Sep 2012
Article Copyright 2009 by DrABELL
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid