Tuesday 6 September 2011

Detect Browser or User Agent from Server-side

My previous post on Detect Browser or User Agent using JavaScript has described a solution on how to do it from client-side. Today, I want to show how to detect user agent or browser type at server-side. It's quite straightforward under ASP.Net framework. Put the following code in your Global.asax so it checks for every new request. The sample code is written in C# and can be in any .Net language.


 
public class Global : System.Web.HttpApplication
{
    void Session_Start(object sender, EventArgs e)
    {
        DetectBrowser();
    }
    // detect browser type by checking user agent
    // and then do specific things for each platform
    private void DetectBrowser()
    {
        string agent = Request.UserAgent.ToLower();
        if (agent.Contains("iphone") ||
            agent.Contains("symbianos") || 
            agent.Contains("ipad") || 
            agent.Contains("ipod") || 
            agent.Contains("android") || 
            agent.Contains("blackberry") || 
            agent.Contains("samsung") || 
            agent.Contains("nokia") || 
            agent.Contains("windows ce") || 
            agent.Contains("sonyericsson") || 
            agent.Contains("webos") || 
            agent.Contains("wap") || 
            agent.Contains("motor") || 
            agent.Contains("symbian"))
        {
            // do your logic here for device specific requests
        }
        else
        {
            // do your logic here for PC/Mac requests
        }
    }
}
 

1 comment: