我一直在尝试在检测到访问站点的设备是移动设备时动态加载母版页。然而,我似乎不能让它加载正确的母版页,因为它总是加载默认的主。无论设备被检测为移动系统还是桌面系统
有人能帮忙吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
public partial class _Default : System.Web.UI.Page
{
protected void Page_PreInt(object sender, EventArgs e)
{
if (Request.Browser.IsMobileDevice == true)
{
MasterPageFile = "~/Mater Pages / Mobile Primary.master";
}
else
{
MasterPageFile = "~/Mater Pages /Primary.master";
base.OnPreInit(e);
}
}
protected void Page_Load(object sender, EventArgs e)
{
// If for any reason this page needs to be made inaccessible then remove the tags on either side of the text//
//Response.Redirect("~/Error Page.aspx");//
}
}
请求浏览器。IsMobileDevice不可靠。下面的助手方法可以检测更多的信息。
如果你想要可靠的设备检测,你需要使用商业服务,如51Degrees。
Event应该是Page_PreInit(而不是Page_PreInt);你打错字了
protected void Page_PreInit(object sender, EventArgs e)
{
// *** For debugging, I inverted if statement. You should do the same. ****
if (!IsMobileBrowser(HttpContext.Current))
MasterPageFile = "~/MaterPages/Primary.master";
else
MasterPageFile = "~/MaterPages/MobilePrimary.master";
// *** You do not need to call base.OnPreInit(e); ***
}
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;
}