Browser detection in ASP.NET

Here is a code snippet for detecting in which Internet browser a user is viewing your site.

Note that I usually use two stylesheets. The first, standard.css, contains the styles interpreted the same way by all browsers. I then use a second stylesheet to add or change any styles rendered differently in different browsers.

In the head tag of the relevant page (a .master page would be a good location) add the following lines (assuming that you use two stylesheets as described above):

<link href="/styles/standard.css" rel="stylesheet" type="text/css" />
<link runat="server" rel="stylesheet" type="text/css" id="stylesheet2" />

In the page_load sub of the same page, add the following code:

'Determine the correct css file depending on the browser

Dim httprequest1 As HttpBrowserCapabilities = Request.Browser

Select Case httprequest1.Browser

Case "IE"
   If httprequest1.Version = "6.0" Then
      stylesheet2.href = "ie6.css"
   End If

Case "Firefox", "Mozilla"
   stylesheet2.href = "firefox.css"

Case Else
   stylesheet2.Href = ""

End Select

In this example, only two browsers are detected but you could of course add more. You can also add additional versions to each browser.

Published Sunday, February 11, 2007 2:01 PM by gcastner

Comments

No Comments