7

I have an application which uses mobile views and desktop views as different html pages. Now I am moving that to Asp.Net core. I am not thinking about Bootstrap due to some technical reasons. I have to detect the request is from Mobile or not in StartUp to load respective Layout page. How can I achieve that ? Looking for something similar to IsMobileDevice. Already tried MvcDeviceDetector 0.1.0-t00349acaa. It didn't worked as I am using .net version 4.6.1.

vishnu
  • 223
  • 1
  • 4
  • 16

5 Answers5

18

I found great library. It's very easy to use. I am not sure is it 100% reliable, but it's covering all my cases.

Example:

    public class HomeController : Controller
    {           
        private readonly IDevice device;   

        public HomeController(IDeviceResolver deviceResolver)
        {                
            this.device = deviceResolver.Device
        }

        public IActionResult Index()
        {
            if(device.Type == DeviceType.Desktop)
            {
               //some logic
            }
            else if(device.Type == DeviceType.Mobile)
            {
               //some logic
            }
            else if(device.Type == DeviceType.Tablet)
            {
               //some logic
            }
        }
     }

Device detection .NET CORE

Thank you Wangkanai

zholinho
  • 460
  • 1
  • 5
  • 17
  • Can we check device globally and not in each controller or action? Actually I wanted to render mobile views for mobile device and desktop views for desktop device – Sweetie Jan 07 '20 at 07:20
  • I think it can be done in middleware on the same way. – zholinho Jan 08 '20 at 21:44
2

You can use the manual method outlined here: https://stackoverflow.com/a/13086894/1419970

Or you can use this library: http://www.nuget.org/packages/51Degrees.mobi/3.2.10.3-beta

Both will do for you.

Community
  • 1
  • 1
MoustafaS
  • 1,991
  • 11
  • 20
  • Unable to resolve '51Degrees.mobi (>= 3.2.9.1)' for '.NETFramework,Version=v4.6.1'. – vishnu Dec 23 '16 at 06:35
  • **Unable to resolve '51Degrees.mobi (>= 3.2.9.1)' for '.NETFramework,Version=v4.6.1'. ** This is the error I am getting when I tried 51degrees. It is not supporting .net version 4.6.1 I guess. – vishnu Dec 23 '16 at 06:37
  • 1
    I guess it will give me a solution. Just I need to change the method to compact with .net core. – vishnu Dec 23 '16 at 06:45
2

Simple solution

     public static class Extentions
        {
            public static bool IsMobile(string userAgent)
            {
                if (string.IsNullOrEmpty(userAgent))
                    return false;
    //tablet
                if (Regex.IsMatch(userAgent, "(tablet|ipad|playbook|silk)|(android(?!.*mobile))", RegexOptions.IgnoreCase))
                    return true;
    //mobile
                const string mobileRegex =
                    "blackberry|iphone|mobile|windows ce|opera mini|htc|sony|palm|symbianos|ipad|ipod|blackberry|bada|kindle|symbian|sonyericsson|android|samsung|nokia|wap|motor";
    
                if (Regex.IsMatch(userAgent, mobileRegex, RegexOptions.IgnoreCase)) return true;
   //not mobile 
                return false;
            }
        }

use:

var isMobile = Extentions.IsMobile(Context.Request.Headers["user-agent"].ToString());
foad abdollahi
  • 1,733
  • 14
  • 32
  • Best solution I've found. No need to install any packages and troubleshoot class relation and proper usage. thx! – Sylwia M Mar 17 '22 at 13:55
1

Or you can use this free library DeviceDetector.NET.

This is a port of the popular PHP device-detector library to C#.

Here is how to use it.

DeviceDetectorNET.DeviceDetector.SetVersionTruncation(VersionTruncation.VERSION_TRUNCATION_NONE); 
var userAgent = Request.Headers["User-Agent"];
var result = DeviceDetectorNET.DeviceDetector.GetInfoFromUserAgent(userAgent);
var output = result.Success ? result.ToString().Replace(Environment.NewLine, "<br />") : "Unknown";
TotPeRo
  • 6,561
  • 4
  • 47
  • 60
0

Here is the solution I use for my .NET6 project using middleware. https://github.com/totpero/DeviceDetector.NET

using DeviceDetectorNET;
       
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.Use(async (context, next) =>
    {
         var detector = new DeviceDetector(context.Request.Headers["User-Agent"].ToString());
         detector.SetCache(new DictionaryCache());
         detector.Parse();

        if (detector.IsMobile())
        {
            context.Items.Remove("isMobile");
            context.Items.Add("isMobile", true);
        }
        else
        {
            context.Items.Remove("isMobile");
            context.Items.Add("isMobile", false);
        }

        context.Items.Remove("DeviceName");
        context.Items.Add("DeviceName", detector.GetDeviceName());

        await next();

    });
}

Usage

  var deviceName = HttpContext.Items["DeviceName"].ToString();
  var isMobile = Convert.ToBoolean(HttpContext.Items["isMobile"]);
Filix Mogilevsky
  • 727
  • 8
  • 13