我想要实现的目标很简单;在我的Web应用程序中的所有视图中,我只有两个剃刀视图,我为他们创建了一个移动版本。 因此,如果他们从移动设备访问应用程序,我需要将用户重定向到这些视图。我在控制器级别上尝试了以下操作,但是当我在不同的移动设备上运行测试时,它没有重定向用户: -
if (Request.Browser.IsMobileDevice)
{
return View("MobileStudentStartAssessment");
}
else {
return View("StudentStartAssessment");
}
那么我可以采用哪种方法来检测大多数移动设备? 感谢
答案 0 :(得分:26)
您可以使用Request.Browser.IsMobileDevice
属性。
答案 1 :(得分:18)
假设您的移动视图适用于所有移动设备(而不是具有特定于设备的视图),您可以检查用户代理字符串以查看应返回的视图。这只是一个例子,但应该让你走得很远:
private static string[] mobileDevices = new string[] {"iphone","ppc",
"windows ce","blackberry",
"opera mini","mobile","palm",
"portable","opera mobi" };
public static bool IsMobileDevice(string userAgent)
{
// TODO: null check
userAgent = userAgent.ToLower();
return mobileDevices.Any(x => userAgent.Contains(x));
}
然后,在您的控制器操作中,您可以调用:
if (MobileHelper.IsMobileDevice(Request.UserAgent))
{
// Return mobile view
}
如果您仍然发现它无法识别您的移动浏览器,请检查调试器中的用户代理字符串,看看是否有可以使用的标识符。
答案 2 :(得分:12)
我使用51degrees.mobi package from nuget。这在检测所有不同的移动设备时更准确。它立即起作用。
当浏览器是移动设备时,我会将其重定向到其他区域。
我还建议您阅读有关该主题的Steve Sandersons blog。
答案 3 :(得分:1)
使用WURFL http://wurfl.sourceforge.net/dotnet_index.php
如果你使用asp.net mvc,你可以使用ActionFilter
public class MobileActionFilterAttribute : ActionFilterAttribute
{
// The WURFL database contains information about a huge number of devices and mobile browsers.
// http://wurfl.sourceforge.net/
// http://wurfl.sourceforge.net/dotnet_index.php
// http://wurfl.sourceforge.net/help_doc.php
private static readonly IWURFLManager WurflManager;
static MobileActionFilterAttribute ()
{
IWURFLConfigurer configurer = new ApplicationConfigurer();
WurflManager = WURFLManagerBuilder.Build(configurer);
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpRequestBase request = filterContext.RequestContext.HttpContext.Request;
// We don't have ARR server for dev environment, so we still need to check to see if the current domain name is the mobile site.
if (request.Url.AbsoluteUri.StartsWith(SiteConfiguration.Current.MobileSiteAddress, StringComparison.OrdinalIgnoreCase))
{
return;
}
// Creates a WURFLRequest object from an ASP.NET HttpRequest object
WURFLRequest wurflRequest = WURFLRequestFactory.CreateRequest(HttpContext.Current.Request);
// Indicates whether the current user agent string refers to a desktop agent.
if (wurflRequest.IsDesktopRequest)
return;
// Get the information about the device
IDevice deviceInfo = WurflManager.GetDeviceForRequest(wurflRequest);
// Tells you if a device is a tablet computer (iPad and similar, regardless of OS)
bool isTablet = string.Equals(deviceInfo.GetCapability("is_tablet") ?? string.Empty, "true", StringComparison.OrdinalIgnoreCase);
if (isTablet)
{
// so we don't show the mobile site for iPad.
return;
}
// Indicates whether the current user agent string refers to a mobile device.
bool isMobileRequest = wurflRequest.IsMobileRequest;
// Tells you if a device is wireless or not. Specifically a mobile phone or a PDA are considered wireless devices, a desktop PC or a laptop are not
bool isWirelessDevice = string.Equals(deviceInfo.GetCapability("is_wireless_device") ?? string.Empty, "true", StringComparison.InvariantCultureIgnoreCase);
if (isMobileRequest && isWirelessDevice)
{
// we can redirect to the mobile site!
filterContext.Result = new RedirectResult(SiteConfiguration.Current.MobileSiteAddress);
}
}
}
答案 4 :(得分:0)
我使用此方法来检测移动设备和桌面
if (eDurar.MobileDetect.DeviceType.Any(m => Request.UserAgent.Contains(m)))
{
Layout = "~/Views/Shared/_mobileLayout.cshtml";
@Html.Partial("mobileIndex");
}
else
{
Layout = "~/Views/Shared/_Layout.cshtml";
@Html.Partial("desktopIndex");
}
答案 5 :(得分:0)
您可以使用
if (Request.Browser["IsMobileDevice"] == "true")
{
//Mobile Browser Detected
}
else
{
//Desktop Browser Detected
}
答案 6 :(得分:0)
使用51Degrees的开源.Net Api,您可以访问https://github.com/51Degrees/dotNET-Device-Detection,您可以检测到各种各样的移动设备。
您可以在51Degrees.config文件中执行与此类似的操作以启用重定向。
<redirect devicesFile="" timeout="20" firstRequestOnly="true"
originalUrlAsQueryString="false" mobileHomePageUrl="~/Mobile/StudentStartAssessment.aspx"
mobilePagesRegex="/Mobile/">
<locations>
<clear />
<location name="noredirect" url="" matchExpression="" enabled="true">
<add property="Url" matchExpression="[&|\?]noredirect" enabled="true" />
</location>
<location name="Mobile" url="~/Mobile/StudentStartAssessment.aspx" matchExpression=""
enabled="true">
<add property="IsMobile" matchExpression="True" enabled="true" />
</location>
</locations>
</redirect>
有关详细信息,请查看此处https://51degrees.com/Developers/Documentation/APIs/NET-V32/Web-Apps/Configuration/Redirect
披露:我为51Degrees工作
答案 7 :(得分:0)
string u = Request.Headers["User-Agent"].ToString(); //Request.ServerVariables["HTTP_USER_AGENT"];
Regex b = new Regex(@"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
Regex v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);
if ((b.IsMatch(u) || v.IsMatch(u.Substring(0, 4))))
{
return "Mobile device";
}
return "Web site";
答案 8 :(得分:0)
请检查以下代码
if (Utils.fBrowserIsMobile())
{
//the device is a mobile device
}
public static class Utils
{
static Regex MobileCheck = new Regex(@"(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);
static Regex MobileVersionCheck = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);
public static bool fBrowserIsMobile()
{
Debug.Assert(System.Web.HttpContext.Current != null);
if (System.Web.HttpContext.Current.Request != null && System.Web.HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"] != null)
{
var u = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"].ToString();
if (u.Length < 4)
return false;
if (MobileCheck.IsMatch(u) || MobileVersionCheck.IsMatch(u.Substring(0, 4)))
return true;
}
return false;
}
}
答案 9 :(得分:0)
要检查请求是否来自移动设备,可以使用
public class Client
{
//...
void Main()
{
//You should use DI tool in here
PersonService personService = new PersonService(new EfPersonRepository());
//or
PersonService personService2 = new PersonService(new MyOrmPersonRepository());
personService.AddPerson(new Person());
//or
personService2.AddPerson(new Person());
//...
}
}
因为这将返回布尔结果。