在我的网站上,我曾经使用默认情况下在任何新的webforms解决方案中创建的两个母版页(即Site.Master& Site.Mobile.Master)。我已经注意到firefox for mobile我的移动母版页永远不会被加载,而是“普通”母版页。使用chrome for mobile或其他浏览器一切正常。 我对我的解决方案进行了实质性更改,现在移动母版页在任何情况下都不会默认加载(包括chrome开发人员工具)。我做了一些研究,这使我得到了这个解决方案,使用chrome工作正常,但仍然使用firefox返回false:
protected void Page_PreInit(object sender, EventArgs e)
{
if (Request.Browser.IsMobileDevice)
{
MasterPageFile = "~/Site.Mobile.Master";
}
}
这里的问题是我必须将它包含在每个aspx页面中。我做了很多研究,必须承认有关它的文档很差。 是不是有一些设置我可以添加到web.config文件或一些代码添加到我的global.asax,以便我不必检查每个aspx页面中的浏览器?
答案 0 :(得分:1)
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;
}