How can i detect if the request is coming from a m

2019-01-22 20:14发布

问题:

what i am trying to achieve is simple; Among all the view which i have in my web application, i have only two razor views that i have created a mobile version for them. so i need to redirect the users to these views if they are accessing the application from their mobile devices. i tried the following on the controller level but it did not redirect the users when i run my test on different mobile devices :-

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

So is there another approach that i can follow which can detect most of the mobile devices? Thanks

回答1:

You can use the Request.Browser.IsMobileDevice property.



回答2:

Assuming your mobile view is intended for all mobile devices (rather than having device-specific views,) you can inspect the user agent string to see which view you should return. This is just an example, but should get you pretty far along:

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

Then, in your controller action, you can call:

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

If you still find it's not recognizing your mobile browser, inspect the user agent string in the debugger and see if there's an identifier you can use.



回答3:

I use the 51degrees.mobi package from nuget. This is more accurate in detecting all the different mobile devices. It worked right away.

When the browser is a mobile device, I redirect it to a different Area.

I also recommend reading Steve Sandersons blog on the topic.



回答4:

Use WURFL http://wurfl.sourceforge.net/dotnet_index.php

If you using asp.net mvc you can use an 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);
        }
    }
}


回答5:

I use this method to detect mobile and desktop

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


回答6:

You can use

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


回答7:

Using 51Degrees' Open source .Net Api, which you can get here, https://github.com/51Degrees/dotNET-Device-Detection, you can detect a huge variety of mobile devices.

You can do something similar to this in the 51Degrees.config file to enable redirect.

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

For more information on this you can look here https://51degrees.com/Developers/Documentation/APIs/NET-V32/Web-Apps/Configuration/Redirect

Disclosure: I work for 51Degrees