7

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.

Cameron
  • 27,963
  • 100
  • 281
  • 483
  • you shouldn't change the code in a way that the answers you already got don't apply anymore... – Yahia Jan 27 '12 at 10:29

3 Answers3

8

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" });
}
Community
  • 1
  • 1
Nikita Ignatov
  • 6,872
  • 2
  • 34
  • 34
1

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

annonymously
  • 4,708
  • 6
  • 33
  • 47
1

IndexOf returns -1 if the string is not found... see MSDN for reference.

Yahia
  • 69,653
  • 9
  • 115
  • 144