移动母版页未自动触发

Mobile master page not automatically triggered

在我的网站上,我曾经使用在任何新的网络表单解决方案中默认创建的两个母版页(即 Site.Master 和 Site.Mobile.Master)。我在 firefox for mobile 上注意到我的移动母版页从未被加载,而是 "normal" 母版页。对于移动设备或其他浏览器,使用 chrome 一切正常。 我对我的解决方案进行了实质性更改,现在移动母版页在任何情况下都不会默认加载(包括 chrome 开发人员工具)。我做了一些研究,使我找到了这个解决方案,它在 chrome 上运行良好,但在 firefox 上仍然 returns 错误:

    protected void Page_PreInit(object sender, EventArgs e)
    {
        if (Request.Browser.IsMobileDevice)
        {
            MasterPageFile = "~/Site.Mobile.Master";
        }
    }

这里的问题是我必须将它包含在每个 aspx 页面中。我做了很多研究并且必须承认关于它的文档很差。 是不是有一些设置可以添加到 web.config 文件或一些代码可以添加到我的 global.asax,这样我就不必在每个 aspx 页面中检查浏览器?

Request.Browser.IsMobileDevice不可靠。下面的辅助方法可以检测更多一点。

如果您希望对每台设备(包括新设备)进行可靠检测,您需要使用商业服务,例如 51Degrees

protected void Page_PreInit(object sender, EventArgs e)
{
    // *** For debugging, I inverted if statement. 
   //      You can reverse it back after debugging. ****
    if (!IsMobileBrowser(HttpContext.Current))
        MasterPageFile = "~/Site.Desktop.Master";
    else
        MasterPageFile = "~/Site.Mobile.Master";    
}

public static bool IsMobileBrowser(HttpContext context)
{
    // first try built in asp.net check
    if (context.Request.Browser.IsMobileDevice)
    {
        return true;
    }

    // then try checking for the http_x_wap_profile header
    if (context.Request.ServerVariables["HTTP_X_WAP_PROFILE"] != null)
    {
        return true;
    }

    // then try checking that http_accept exists and contains wap
    if (context.Request.ServerVariables["HTTP_ACCEPT"] != null &&
        context.Request.ServerVariables["HTTP_ACCEPT"].ToLower().Contains("wap"))
    {
        return true;
    }

    // Finally check the http_user_agent header variable for any one of the following
    if (context.Request.ServerVariables["HTTP_USER_AGENT"] != null)
    {
        // List of all mobile types
        string[] mobiles =
            new[]
            {
                "android", "opera mini", "midp", "j2me", "avant", "docomo", "novarra", "palmos", "palmsource",
                "240×320", "opwv", "chtml",
                "pda", "windows ce", "mmp/", "blackberry", "mib/", "symbian", "wireless", "nokia", "hand", "mobi",
                "phone", "cdm", "up.b", "audio", "sie-", "sec-", "samsung", "htc", "mot-", "mitsu", "sagem", "sony",
                "alcatel", "lg", "eric", "vx", "nec", "philips", "mmm", "xx", "panasonic", "sharp", "wap", "sch",
                "rover", "pocket", "benq", "java", "pt", "pg", "vox", "amoi", "bird", "compal", "kg", "voda",
                "sany", "kdd", "dbt", "sendo", "sgh", "gradi", "dddi", "moto", "iphone"
            };

        // Check if the header contains that text
        var userAgent = context.Request.ServerVariables["HTTP_USER_AGENT"].ToLower();

        return mobiles.Any(userAgent.Contains);
    }

    return false;
}