Skip to content

ASP.NET Core Detection with Responsive View for identifying details about client device, browser, engine, platform, & crawler. Responsive middleware for routing base upon request client device detection to specific view.

main
Switch branches/tags
Code

ASP.NET Core Detection with Responsive View

ASP.NET Core Detection service components for identifying details about client device, browser, engine, platform, & crawler. Responsive middleware for routing base upon request client device detection to specific view. Also in the added feature of user preference made this library even more comprehensive must for developers whom to target multiple devices with view rendered and optimized directly from the server side.

Please show me some love and click the

ASP.NET Core Detection

Build status NuGet Badge NuGet Badge MyGet Badge

GitHub Open Collective Patreon

Build history

This project development has been in the long making of my little spare time. Please show your appreciation and help me provide feedback on you think will improve this library. All developers are welcome to come and improve the code by submit a pull request. We will have constructive good discussion together to the greater good.

Installation

Installation of detection library is now done with a single package reference point. If you are using ASP.NET Core 2.X please use detection version 2.0 installation.

PM> install-package Wangkanai.Detection

This library host the component services to resolve the access client device type. To the servoces your web application is done by configuring the Startup.cs by adding the detection service in the ConfigureServices method.

public void ConfigureServices(IServiceCollection services)
{
    // Add detection services container and device resolver service.
    services.AddDetection();

    // Needed by Wangkanai Detection
    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromSeconds(10);
        options.Cookie.HttpOnly = true;
        options.Cookie.IsEssential = true;
    });

    // Add framework services.
    services.AddControllersWithViews();
}
  • AddDetection() Adds the detection services to the services container.

The current device on a request is set in the Responsive middleware. The Responsive middleware is enabled in the Configure method of Startup.cs file. Make sure that you have app.UseDetection() before app.UseRouting.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseDetection();
    
    app.UseRouting();

    app.UseSession();

    app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());
}

Adding the TagHelper features to your web application with following in your _ViewImports.cshtml

@using WebApplication1

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Wangkanai.Detection

Detection Service

After you have added the basic of the detection services, let us learn how to utilized the library in your web application. In which we have got the help from dependency injection to access all functionality of IDetectionService has to offer.

Make your web app able to detect what client is accessing

Detection service support usage in both Model-View-Controller (MVC) and Razor Pages.

MVC

Here is how you would use the library in Controller of a MVC pattern by injecting the detection service into the constructor of the controller.

public class AboutController : Controller
{
    private readonly IDetectionService _detectionService;

    public AboutController(IDetectionService detectionService)
    {
        _detectionService = detectionService;
    }

    public IActionResult Index()
    {
        return View(_detectionService);
    }
}

Razor Pages

For razor pages web application that only have the pages without PageModel behind, you can access the detection service via the @inject tag after the @page in your .cshtml files. Here would be the example below;

@page
@inject Wangkanai.Detection.Services.IDetectionService DetectionService
@{
    ViewData["Title"] = "Detection";
}
<ul>
    <li>@DetectionService.Device.Type</li>
    <li>@DetectionService.Browser.Name</li>
    <li>@DetectionService.Platform.Name</li>
    <li>@DetectionService.Engine.Name</li>
    <li>@DetectionService.Crawler.Name</li>
</ul>

What if you razor pages use the code behind model, you can still inject the detection service into it via the constructor just similar way as MVC controller does it.

public class IndexModel : PageModel
{
    private readonly IDetectionService _detectionService;

    public IndexModel(IDetectionService detectionService)
    {
        _detectionService = detectionService;
    }
    
    public void OnGet()
    {
        var device = _detectionService.Device.Type;
    }
}

Detection in Middleware

Would you think that Middleware can also use this detection service. Actually it can! and our Responsive make good use of it too. Let us learn how that you would use detection service in your custom middleware which we would use the Per-request middleware dependencies. But why would we use pre-request injection for our middleware you may ask? Easy! because every user is unique. Technically answer would be that IDetectionService by using TryAddTransient<TInterface, TClass> where you can learn more about transient. If you inject IDetectionServices into the middleware constructor, then the service would become a singleton. Meaning to subject to application not per client request.

So now we know about the basic lets look at the code:

public class MyCustomMiddleware
{
    private readonly RequestDelegate _next;

    public MyCustomMiddleware(RequestDelegate next)
    {
        _next = next ?? throw new ArgumentNullException(nameof(next));
    }

    public async Task InvokeAsync(HttpContext context, IDetectionService detection)
    {
        if(detection.Device.Type == Device.Mobile)
            context.Response.WriteAsync("You are Mobile!");

        await _next(context);
    }
}

Detection Fundamentals

Detection services would extract information about the visitor web client by parsing the user agent that the web browser gives to the web server on every http/https request. We would make the assumption that every requester is using common Mozilla syntax: Mozilla/[version] ([system and browser information]) [platform] ([platform details]) [extensions]. If detection service can not identify the information, it will we have give you Unknown enum flag. There are total of 5 resolver services the our detection services.

Device Resolver

This would be the basic resolver that you might be thinking using to identify what kind client Device is access your web app, which include Desktop, Tablet, and Mobile for the basic stuff. While we can also use to identify is the device a Watch, Tv, Game Console, Car, and Internet of Things.

var isMobile = detectionService.Device.Type == Device.Mobile;

Browser Resolver

Moving the stack we get what Browser is the client using to access your web app. We only include the common web browser detection starting from Chrome, Internet Explorer, Safari, Firefox, Edge, and Opera. For the rest we would mark them as others or unknown (aka Crawler).

var isIE = detectionService.Browser.Name == Browser.InternetExplorer;

Platform Resolver

Now we can also identify what Platform is the client using to access your web app starting in version 3.0. We got Windows, Mac, iOS, Linux, and Android.

var isMac = detectionService.Platform.Name == Platform.Mac;

Engine Resolver

Now we can also identify what Engine is the client using to access your web app starting in version 3.0. We got WebKit, Blink, Gecko, Trident, EdgeHTML, and Servo.

var isTrident = detectionService.Engine.Name == Engine.Trident;

Crawler Resolver

This would be something that web analytics to keep track on how are web crawler are access your website for indexing. We got starting everybody favorite that is Google, Bing, Yahoo, Baidu, Facebook, Twitter, LinkedIn, WhatsApp, and Skype.

var isGoogle = detectionService.Crawler.Name == Crawler.Google;

Detection Options

There are basic options that you can add to detection services. Like to adding something that detection does not identify by default to the Others list.

public void ConfigureServices(IServiceCollection services)
{
    // Add responsive services.
    services.AddDetection(options =>
    {
        options.Crawler.Others.Add("goodbot");
    });

    // Add framework services.
    services.AddControllersWithViews();
}

Responsive Service

This is where thing get more interesting that is built upon detection service, or matter a fact detection service was built because of responsive service. The concept is that we would like to have views that correspond to what kind of device to accessing to our web app.

Responsive MVC

Responsive Views for MVC has 2 format for you to utilize. First is would be to most common is Suffix and the secord format is SubFolder. Lets make this follow example a suffix as of my opinionated would be the most common way to managed all the views. This suffix format is done by add device type before the file extension .cshtml like .mobile.cshtml. Below is how you would structure your Views folder.

Responsive view file structure

Responsive Razor Pages

Responsive for razor pages newly added in wangkanai.detection 3.0. This enable completed responsive in asp.net core ecosystem. Same like Views in MVC we have suffix format where we add the device type in before the file extension .cshtml like .mobile.cshtml.

Responsive razor pages file structure

Responsive Tag Helpers

The next exciting feature add in wangkanai.detection 3.0 is Tag Helpers. This make you able to use the same view and just show/hide specific part of the views to the client base upon their type, this include Device, Browser, Platform, Engine, and Crawler that our detection resolver could determine from the resolver parsing services.

<device include="mobile">is mobile</device>
<device exclude="mobile">not mobile</device>
<browser include="chrome">is chrome</browser>
<browser exclude="chrome">not chrome</browser>
<platform include="windows">is windows</platform>
<platform exclude="windows">not windows</platform>
<engine include="blink">is blink</engine>
<engine exclude="blink">not blink</engine>
<crawler include="google">is google</crawler>
<crawler exclude="google">not google</crawler>

User Preference

When a client visit your web application by using a mobile device and you have responsive view for mobile device. But the visitor would like to view the web app with a desktop view, their click this link to change their preference to desktop view.

<a href="/Detection/Preference/Prefer">
    <div class="alert alert-light" role="alert">
        Desktop version
    </div>
</a>

If the client selected to view in desktop view, he/she can switch back mobile view by the follow example;

<preference only="mobile">
    <a href="/Detection/Preference/Clear">
        <div class="alert alert-light" role="alert">
            Switch to mobile version
        </div>
    </a>
</preference>

Responsive Options

You can customize the default behaviour of how responsive service would react to client request. You can go in deep by examining ResponsiveOptions.

public void ConfigureServices(IServiceCollection services)
{
    // Add responsive services.
    services.AddDetection(options =>
    {
        options.Responsive.DefaultTablet  = Device.Desktop;
        options.Responsive.DefaultMobile  = Device.Mobile;
        options.Responsive.DefaultDesktop = Device.Desktop;
        options.Responsive.IncludeWebApi  = false;
        options.Responsive.Disable        = false;
        options.Responsive.WebApiPath     = "/Api";
    });

    // Add framework services.
    services.AddControllersWithViews();
}
  • AddDetection(Action<DetectionOptions> options) Adds the detection services to the services container.

Directory Structure

  • src - The source code of this project lives here
  • test - The test code of this project lives here
  • collection - Collection of sample user agents for lab testing
  • sample - Contains sample web application of usage
  • doc - Contains the documentation on how utilized this library

Contributing

All contribution are welcome, please contact the author.

Contributors

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

Individuals Contributors

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

About

ASP.NET Core Detection with Responsive View for identifying details about client device, browser, engine, platform, & crawler. Responsive middleware for routing base upon request client device detection to specific view.

Topics

Resources

License