繁体   English   中英

如何在我的 asp.net MVC 3 中检测请求是否来自移动浏览器

[英]How can i detect if the request is coming from a mobile browser in my asp.net MVC 3

我想要实现的很简单; 在我的 web 应用程序中的所有视图中,我只有两个 razor 视图,我为它们创建了一个移动版本。 所以如果他们从他们的移动设备访问应用程序,我需要将用户重定向到这些视图。 我在 controller 级别上尝试了以下操作,但当我在不同的移动设备上运行测试时它没有重定向用户:-

if (Request.Browser.IsMobileDevice)
            {
                return View("MobileStudentStartAssessment");
            }
            else {
                return View("StudentStartAssessment");
            }

那么我可以采用另一种可以检测大多数移动设备的方法吗? 谢谢

您可以使用Request.Browser.IsMobileDevice属性。

假设您的移动视图适用于所有移动设备(而不是具有特定于设备的视图),您可以检查用户代理字符串以查看您应该返回哪个视图。 这只是一个例子,但应该会让你走得很远:

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));
}

然后,在您的 controller 操作中,您可以调用:

if (MobileHelper.IsMobileDevice(Request.UserAgent))
{
    // Return mobile view
}

如果您仍然发现它无法识别您的移动浏览器,请检查调试器中的用户代理字符串,看看是否有您可以使用的标识符。

我使用来自 nuget 的 51degrees.mobi package 这在检测所有不同的移动设备时更加准确。 它立即起作用。

当浏览器是移动设备时,我将其重定向到不同的区域。

我还推荐阅读Steve Sandersons 关于该主题的博客

使用 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);
        }
    }
}

我用这个方法检测手机和桌面

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");
}

您可以使用

   if (Request.Browser["IsMobileDevice"] == "true")
        {
        //Mobile Browser Detected
        }
   else
      {
       //Desktop Browser Detected
      }

使用 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="[&amp;|\?]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 工作


 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";

请检查以下代码

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;
            }
        }

要检查请求是否来自移动设备,您可以使用

HttpContext.Request.Browser.IsMobileDevice

因为这将返回 boolean 结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM