Search code examples
asp.net-mvcasp.net-mvc-4global-asaxdevice-detection51degrees

Global.asax device detection with 51 degrees cloud API


Can anyone help? I want to use the free service from 51Degrees not the Lite version however the Cloud API (https://51degrees.com/compare-data-options).

I am trying to set my Global.asax to have a display mode for "tablet" and "mobile" so I can use:

  • index.cshtml
  • index.tablet.cshtml
  • index.mobile.cshtml

The following works when not using 51 Degrees. Has anyone got an example how to integrate the 51 Degrees Cloud API with the global.asax to filter for tablet/mobile.

https://51degrees.com/Support/Documentation/APIs/Cloud-API/NET-Cloud

DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("Tablet")
            {
            ContextCondition = (ctx =>
            ctx.Request.UserAgent.IndexOf("iPad", StringComparison.OrdinalIgnoreCase) >= 0 ||
            ctx.Request.UserAgent.IndexOf("Android", StringComparison.OrdinalIgnoreCase) >= 0  &&
            ctx.Request.UserAgent.IndexOf("Mobile", StringComparison.OrdinalIgnoreCase) <= 0
            )
            });

Thanks Tommy


Solution

  • You can get the value of DeviceType which can be Desktop, SmartPhone or Tablet (plus a few other things) by using the first C# example on the page you linked. Something like:

    string json = webClient.DownloadString(String.Format(
      "https://cloud.51degrees.com/api/v1/{0}/match?user-agent={1}&values=DeviceType",
      yourLicenceKey, ctx.Request.UserAgent));
    
    dynamic match = Newtonsoft.Json.Linq.JObject.Parse(json);
    

    Then your condition for tablet would be:

    DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("Tablet")
                {
                ContextCondition = (ctx =>
                    match.Values.DeviceType.IndexOf("Tablet", StringComparison) != -1))
                });
    

    You can query the possible values of DeviceType with the URL

    https://cloud.51degrees.com/api/v1/[you licence key]/values?propertyname=DeviceType
    

    or alternatively, use the IsMobile, IsSmartPhone, IsTablet and IsDesktop properties which return true or false.