Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading the userAgent with C#

I have the following code which reads the userAgent and does some logic based on the values matched using indexOf:

String userAgent;
userAgent = Request.UserAgent;
// If it's not IE
if (userAgent.IndexOf("MSIE") < 0)
{
    return RedirectToAction("Index", "Home", new { area = "Dashboard" });
}
// If it's IE BUT ChromeFrame
else if(userAgent.IndexOf("ChromeFrame") > -1)
{
    return RedirectToAction("Index", "Home", new { area = "Dashboard" });
}
// It's just IE
else
{
    return View("ChromeFrame");
}

If it's IE then it should return the view or if its IE but contains ChromeFrame then it should redirect and it's another browser then it should redirect as well.

I think the problem is with the > 0 part of the code. What is the correct way of comparing info? Thanks.

like image 956
Cameron Avatar asked Jan 27 '12 10:01

Cameron


2 Answers

Just use the contains method, which will make your code less cryptic and less error-prone.

if (userAgent.Contains("MSIE"))
{
    return RedirectToAction("Index", "Home", new { area = "Dashboard" });
}
like image 78
Nikita Ignatov Avatar answered Oct 11 '22 08:10

Nikita Ignatov


You should be using > -1 as otherwise it will not work if the substring is at the beginning of the string.

like image 20
annonymously Avatar answered Oct 11 '22 09:10

annonymously