How to determine Browser type from Server side using ASP.NET & C#?

Viewed 24036

I want to determine the browser type in code-behind file using C# on ASP.NET page.

If it is IE 6.0, I have to execute certain lines of code.

How can I determine the browser type?

4 Answers

You can use Request.Browser to identify the browser info. These MSDN 1 & 2 article gives more info abt this.

System.Web.HttpBrowserCapabilities browser = Request.Browser;
string s = "Browser Capabilities\n"
    + "Type = "                    + browser.Type + "\n"
    + "Name = "                    + browser.Browser + "\n"
    + "Version = "                 + browser.Version + "\n"
    + "Major Version = "           + browser.MajorVersion + "\n"
    + "Minor Version = "           + browser.MinorVersion + "\n"
    + "Platform = "                + browser.Platform + "\n"
    + "Is Beta = "                 + browser.Beta + "\n"
    + "Is Crawler = "              + browser.Crawler + "\n"
    + "Is AOL = "                  + browser.AOL + "\n"
    + "Is Win16 = "                + browser.Win16 + "\n"
    + "Is Win32 = "                + browser.Win32 + "\n"
    + "Supports Frames = "         + browser.Frames + "\n"
    + "Supports Tables = "         + browser.Tables + "\n"
    + "Supports Cookies = "        + browser.Cookies + "\n"
    + "Supports VBScript = "       + browser.VBScript + "\n"
    + "Supports JavaScript = "     + 
        browser.EcmaScriptVersion.ToString() + "\n"
    + "Supports Java Applets = "   + browser.JavaApplets + "\n"
    + "Supports ActiveX Controls = " + browser.ActiveXControls 
          + "\n";

You may also want to look at: Request.ServerVariables.

I have used:

string UserAgent = Request.ServerVariables["HTTP_USER_AGENT"];
Response.Write("User: " + UserAgent);
if(UserAgent.Contains("MSIE")) {
   //do something
} 

to show me what browser is being used. This can give you a response for IE similar to:

User: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.21022; Tablet PC 2.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.1.4322)

Depending on your version of IE or other browser. Firefox gives me:

User: Mozilla/5.0 (Windows NT 6.0; rv:11.0) Gecko/20100101 Firefox/11.0

It is important to note: I would use the ServerVariables over the Browser Capabilities because using BrowserCapabilities on Chrome will currently return "Desktop" which seems to be the same for Safari when I check it on a mac.

Related