用C#读取userAgent

Cam*_*ron 7 c# asp.net-mvc-3

我有以下代码读取userAgent并根据使用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");
}
Run Code Online (Sandbox Code Playgroud)

如果它是IE,那么它应该返回视图,或者如果它的IE但包含ChromeFrame,那么它应该重定向,它是另一个浏览器,那么它也应该重定向.

我认为问题在于> 0代码的一部分.比较信息的正确方法是什么?谢谢.

Nik*_*tov 8

只需使用 contains方法,这将使您的代码不那么神秘,不易出错.

if (userAgent.Contains("MSIE"))
{
    return RedirectToAction("Index", "Home", new { area = "Dashboard" });
}
Run Code Online (Sandbox Code Playgroud)


ann*_*sly 1

您应该使用> -1as 否则,如果子字符串位于字符串的开头,它将不起作用。