【问题标题】:Reading the userAgent with C#用 C# 读取 userAgent
【发布时间】:2012-02-20 08:27:51
【问题描述】:

我有以下代码读取 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");
}

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

我认为问题出在代码的&gt; 0 部分。比较信息的正确方法是什么?谢谢。

【问题讨论】:

  • 你不应该以你已经得到的答案不再适用的方式更改代码......

标签: c# asp.net-mvc-3


【解决方案1】:

只需使用contains method,这将使您的代码不那么神秘,更不容易出错。

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      IndexOf 如果未找到该字符串,则返回 -1...参见MSDN 以供参考。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        相关资源
        最近更新 更多