Request.Browser.IsMobileDevice是不可靠的。以下幫助程序方法可能會檢測到更多一點。
如果你想要可靠的設備檢測,你想要使用商業服務,如51Degrees。
事件應被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;
}
您確認文件存在於這些位置嗎?在這兩種情況下,你都拼錯了主文字。另外,你的文件名中有空格,但是從這裏粘貼代碼可能會出現問題? – ScoobyDrew18
這些文件肯定位於root〜/ Mater頁面中(沒有得到重命名),Mobile primary.master文件在移動設備和主要文件之間有一個空格。那可能是導致錯誤的原因嗎? –
@WillR對於動態主頁面綁定,我認爲你需要進一步關注[這裏](http://www.asp.net/web-forms/overview/older-versions-getting-started/master-pages/specifying -the-master-page-programmatically-cs)和[here](https://msdn.microsoft.com/en-us/library/c8y19k6h.aspx) –