Check out the latest documentation.

Introduction

The easiest way to see how 51Degrees .NET API can be used within MVC is to open up the Visual Studio project from the GitHub repository and look at the MVC project inside the Examples folder. Below, we will go through the steps to recreate this project.

Installing

The first step is to install 51Degrees into your project. This example uses a new Visual Studio 2013 ASP.NET website with MVC NuGet package installed, but it should work for any version of Visual Studio, providing the project is using .NET 4 or above.

51Degrees can be found in Visual Studios NuGet package manager, or can be downloaded from GitHub. The package comes with an aspx test page which is not needed for this, so 'Mobile/Default.aspx' can be deleted.

All configuration is administered in 51Degrees.config. The redirect element in that file can be removed as redirection doesn't fit very well in MVC because controllers cannot be reused.

Code and Explanation

The first stage of using 51Degrees device detection in MVC is creating a model. This Device model can access the Match object in two ways:

Accessing the Match object directly

This is the most efficient method as it returns the requested property directly from the Match object

Reflecting the Match object properties

This uses reflection to set all the properties of the Device object, so with a large number of properties will be a less efficient method.

Full Source File
										
        /// <summary>
        /// Instance of a device detection match to use for device properties.
        /// </summary>
        private readonly Match _match;

        // These properties are fetched only when requested by the view. This 
        // can be a more efficient method of accessing property values as 
        // they're only retrieved when requested.
        public bool IsMobile 
        { 
            get 
            { 
                return _match["IsMobile"] != null ? 
                    _match["IsMobile"].ToBool() : 
                    false; 
            } 
        }
        public int ScreenPixelsHeight 
        { 
            get 
            { 
                return _match["ScreenPixelsHeight"] != null ?
                    (int)_match["ScreenPixelsHeight"].ToDouble() :
                    0; 
            } 
        }
        public int ScreenPixelsWidth
        {
            get
            {
                return _match["ScreenPixelsWidth"] != null ?
                    (int)_match["ScreenPixelsWidth"].ToDouble() :
                    0;
            }
        }

        // These properties are populated in the constructor with
        // 51Degrees properties of the same name. More can be added
        // as long as their name is the same as the 51Degrees
        // property and are string types. More properties
        // are listed at https://51degrees.com/Resources/Property-Dictionary
        public string HardwareVendor { get; private set; }
        public string HardwareModel { get; private set; }
        public string PlatformVendor { get; private set; }
        public string PlatformName { get; private set; }
        public string PlatformVersion { get; private set; }
        public string BrowserVendor { get; private set; }
        public string BrowserName { get; private set; }
        public string BrowserVersion { get; private set; }
        
        /// <summary>
        /// Uses reflection to see if there is a 51Degrees property with the 
        /// same name as a Device class property. This means getting a new 
        /// 51Degrees property in this object only requires creating a 
        /// property with that name.
        /// </summary>
        /// <param name="match">Instance of a device detection match</param>
        internal Device(Match match)
        {
            _match = match;
            foreach (var classProperty in this.GetType().GetProperties().Where(p => 
                p.PropertyType == typeof(string)))
            {
                var values = match[classProperty.Name];
                if (values != null && values.Count > 0)
                {
                    // There is a value for the property. Set the value
                    // now.
                    classProperty.SetValue(this, values.ToString());
                }
                else
                {
                    // Property is not contained in the active 51Degrees
                    // data set. Display a link to switch the data set
                    // and re-run the example.
                    classProperty.SetValue(this, SWITCH_HTML);
                }
            }
        }


										
Full Source File

The BaseController overrides the initialize method and creates a Match object. It creates a new instance of the Device model using this match and makes it available in the ViewBag for use in cshtml pages. It also exposes the Match object directly via the ViewBag (the more efficient method).

Now any view from a controller extending BaseController can access these objects like

								
@ViewBag.Device.IsMobile
@ViewBag.Match.getValue("IsMobile")

								

to print the IsMobile property for Device and Match objects respectively.

Using the Match object also makes it easy to access data set properties and match metrics like,

								
@ViewBag.Match.DataSet.Published
@ViewBag.Match.Method

								

to print the data set published date and match method from the Match object.

Full Source File
										
    public class BaseController : Controller
    {
        /// <summary>
        /// If there is an active device detection provider then use this to
        /// add dynamic properties to the ViewBag. 
        /// </summary>
        /// <para>
        /// The Device property of the ViewBag is set to a new MVC model 
        /// instance which copies properties from the device match result.
        /// </para>
        /// <para>
        /// The Match property of the ViewBag is set to directly expose the
        /// match instance returned from device detection.
        /// </para>
        /// <param name="requestContext"></param>
        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);
            
            if (WebProvider.ActiveProvider != null)
            {
                // Perform device detection on the headers provided in the
                // request.
                var match = WebProvider.ActiveProvider.Match(
                    requestContext.HttpContext.Request.Headers);
                
                // Create a model that is based on the match request from
                // device detection.
                ViewBag.Device = new Device(match);

                // Also expose the match result directly in the ViewBag
                // to compare the different access methods when used in the 
                // view.
                ViewBag.Match = match;
            }

            // Get the HTTP headers from the request to display their values in
            // the view.
            ViewBag.RequestHeaders =
                requestContext.HttpContext.Request.Headers;
        } 
    }


										
Full Source File

Example MVC Mobile Output

You should now be able to navigate to this page and see information about your device displayed. If you're using a desktop browser then the information returned will be limited. To see a fuller set of data, either use the device emulation capabilities of the web browser to imitate a smartphone or tablet, or if possible use an actual mobile device.

MVCMobilePage