我们目前拥有一个大型的ASP.Net WebForms网站,我们刚开始将其部分转换为ASP.Net MVC。
我们想创建一个专门针对移动客户端的站点版本,并希望从使用MVC开始。
我知道MVC默认支持为移动客户端服务以.mobile结尾的视图文件。但我的问题是 - 我应该如何设置才能让桌面客户端仍然使用default.aspx而移动客户端被重定向到/home呢?
我们目前拥有一个大型的ASP.Net WebForms网站,我们刚开始将其部分转换为ASP.Net MVC。
我们想创建一个专门针对移动客户端的站点版本,并希望从使用MVC开始。
我知道MVC默认支持为移动客户端服务以.mobile结尾的视图文件。但我的问题是 - 我应该如何设置才能让桌面客户端仍然使用default.aspx而移动客户端被重定向到/home呢?
浏览器检测的代码应该放在一个基类中,所有页面都继承自该基类。请尝试如下代码:
protected void Page_Load(object sender, EventArgs e)
{
if (IsMobileBrowser())
{
Response.Redirect("/home");
return;
}
// your other code
}
public static bool IsMobileBrowser()
{
//GETS THE CURRENT USER CONTEXT
HttpContext context = HttpContext.Current;
//FIRST TRY BUILT IN ASP.NT 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;
}
//AND FINALLY CHECK THE HTTP_USER_AGENT
//HEADER VARIABLE FOR ANY ONE OF THE FOLLOWING
if (context.Request.ServerVariables["HTTP_USER_AGENT"] != null)
{
//Create a list of all mobile types
string[] mobiles =new[]
{
"midp", "j2me", "avant", "docomo",
"novarra", "palmos", "palmsource",
"240x320", "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", "jb", "dddi",
"moto", "iphone"
};
//Loop through each item in the list created above
//and check if the header contains that text
foreach (string s in mobiles)
{
if(context.Request.ServerVariables["HTTP_USER_AGENT"].ToLower().Contains(s.ToLower()))
{
return true;
}
}
}
return false;
}
试试这样
if (request.Browser.IsMobileDevice)
{
//rediret the user to mobile views
}
请确保您移除了WebForm视图引擎。像这样:MobileCompatibleViewEngine
ViewEngines.Engines.Remove(ViewEngines.Engines.OfType<WebFormViewEngine>().First());
ViewEngines.Engines.Add(new MobileCapableWebFormViewEngine()); // this will come from Nuget Package.
将以下代码编写到Global.asax中。
如果用户通过桌面访问网站,它将自动重定向到桌面网站,无论用户是通过Android手机访问,它都将自动重定向到移动网站。
protected void Application_Start()
{
DisplayModes.Modes.Insert(0, new DefaultDisplayMode("Android")
{
ContextCondition = (context => context.Request.UserAgent.IndexOf
("Android", StringComparison.OrdinalIgnoreCase) >= 0)
});
DisplayModes.Modes.Insert(0, new DefaultDisplayMode("WindowsPhone")
{
ContextCondition = (context => context.Request.UserAgent.IndexOf
("Windows Phone OS", StringComparison.OrdinalIgnoreCase) >= 0)
});
}