检测移动浏览器并重定向

4

我希望能够使用我的.cs代码,无论是在Page_PreInit还是Page_Load中检测移动浏览器并进行重定向。我找到了以下内容:

protected void Page_PreInit(object sender, EventArgs e) 
{ 
    if (Request.Browser.IsMobileDevice) 
    { 
        { 
          Response.Redirect("~/default_mobile.aspx"); 
        }

    } 
} 

它似乎不起作用。有人能提供一些修正建议吗?此外,您是否知道一个例子,可以不进行重定向,而仅在.aspx页面上用另一个元素替换(即,在iOS设备上将Silverlight电影替换为静态图像)。


你的代码对我来说运行良好。 - John Koerner
2个回答

2
这篇MSDN文档解释了如何在Page_Load上下文中使用.IsMobileDevice,很容易适应您的需求。同时请查看另一个答案,以及51Degrees,一个检测移动设备和浏览器的类库,可以增强.NET可用的信息。

嗨,感谢您提供这个……我已经阅读了它,并在页面上尝试了测试。它可以加载,也可以读取代码,但是对于所有设备(包括iPad和iPhone),它都会显示“浏览器不是移动设备”。我需要在C#代码后台页面的顶部添加汇编引用吗? - user1628753
再次感谢...我有一个问题不太清楚--为了让我的上述代码工作 ((Request.Browser.IsMobileDevice) -- 我需要安装类库,比如51Degrees吗? - user1628753
不是必须的,但51Degrees[他们称]解决了一些问题,比如无法检测到新的移动浏览器等。 - istepaniuk
@user1628753,Request.Browser.IsMobileDevice是C#内置的,而51Degrees是一个完全独立的Nuget包。它们彼此独立。 - John Washam

0
在项目中添加一个全局应用类,并在其中编写代码,代码位于 Session_Start 函数中。
protected void Session_Start(object sender, EventArgs e)
{

            HttpRequest httpRequest = HttpContext.Current.Request;
            if (httpRequest.Browser.IsMobileDevice)
            {
                string path = httpRequest.Url.PathAndQuery;
               bool isOnMobilePage = path.StartsWith("/Mobile/",
                                                      StringComparison.OrdinalIgnoreCase);
                if (!isOnMobilePage)
                {
                    string redirectTo = "~/Mobile/";

                    // Could also add special logic to redirect from certain 
                    // recognised pages to the mobile equivalents of those 
                    // pages (where they exist). For example,
                    // if (HttpContext.Current.Handler is UserRegistration)
                    //     redirectTo = "~/Mobile/RegistrationMobile.aspx";

                    HttpContext.Current.Response.Redirect(redirectTo);
                }
            }   
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接