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

本文关键字:浏览器 移动 我的 asp MVC net 何检测 检测 是否 请求 | 更新日期: 2023-09-27 18:05:13

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

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

那么,是否有另一种方法,我可以遵循,可以检测大多数移动设备?由于

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

您可以使用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));
}
然后,在你的控制器动作中,你可以调用:
if (MobileHelper.IsMobileDevice(Request.UserAgent))
{
    // Return mobile view
}

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

我用51度。Mobi包从nuget。这在检测所有不同的移动设备时更加准确。它立即起作用了。

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

我还推荐阅读Steve sanderson关于这个主题的博客。

使用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,您可以检测各种各样的移动设备。

你可以在51度做类似的事情。配置文件以启用重定向。

<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

,因为这将返回一个布尔值结果。