Reading the userAgent with C#

2019-04-26 18:17发布

问题:

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.

回答1:

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" });
}


回答2:

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



回答3:

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