【问题标题】:Detect mobile browser and redirect检测移动浏览器并重定向
【发布时间】:2013-01-13 18:51:09
【问题描述】:

我想使用我的 .cs 代码隐藏(Page_PreInit 或 Page_Load)来检测移动浏览器并进行重定向。我遇到了这个:

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

    } 
} 

它似乎不起作用。有人可以建议更正吗?另外,您是否知道不重定向的示例,而只是将 .aspx 页面上的元素替换为另一个元素(即,将 Silverlight 电影替换为 iOS 设备的静止图像。)

【问题讨论】:

  • 你的代码适合我。

标签: c# redirect mobile


【解决方案1】:

This MSDN document 解释了如何在Page_Load 的上下文中使用.IsMobileDevice。使其适应您的需求应该是微不足道的。

也检查this other answer

还有51Degrees,一个检测移动设备和浏览器的类库,增强了 .NET 可用的信息。

【讨论】:

  • 嗨,谢谢你...我读了它并在一个页面上尝试了测试。它会加载、读取代码,但会为所有内容(包括 iPad 和 iPhone)显示“浏览器不是移动设备”。我是否需要将程序集引用添加到 C# 代码隐藏页面的顶部?
  • 再次感谢...我不清楚一件事-我上面的代码可以工作((Request.Browser.IsMobileDevice)-我需要安装一个像51Degrees这样的类库吗?
  • 不是必需的,但 51Degrees [他们声称] 解决了一些问题,例如未检测到新的移动浏览器等。
  • @user1628753, Request.Browser.IsMobileDevice 是 C# 内置的,而 51Degrees 是一个完全独立的 Nuget 包。它们相互独立。
【解决方案2】:

在项目中添加一个全局应用类,在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);
                }
            }   
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多