Wangkanai.Detection 4.0.0-beta4

Prefix Reserved
This is a prerelease version of Wangkanai.Detection.
There is a newer version of this package available.
See the version list below for details.
dotnet add package Wangkanai.Detection --version 4.0.0-beta4                
NuGet\Install-Package Wangkanai.Detection -Version 4.0.0-beta4                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Wangkanai.Detection" Version="4.0.0-beta4" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Wangkanai.Detection --version 4.0.0-beta4                
#r "nuget: Wangkanai.Detection, 4.0.0-beta4"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Wangkanai.Detection as a Cake Addin
#addin nuget:?package=Wangkanai.Detection&version=4.0.0-beta4&prerelease

// Install Wangkanai.Detection as a Cake Tool
#tool nuget:?package=Wangkanai.Detection&version=4.0.0-beta4&prerelease                

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

<img src="https://raw.githubusercontent.com/wangkanai/Detection/main/asset/aspnet-core-detection-3.svg?sanitize=true" width="650" alt="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]. <a href="https://github.com/wangkanai/Detection/graphs/contributors"><img src="https://opencollective.com/wangkanai/contributors.svg?width=890&button=false" /></a>

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]

<a href="https://opencollective.com/wangkanai/organization/0/website"><img src="https://opencollective.com/wangkanai/organization/0/avatar.svg"></a> <a href="https://opencollective.com/wangkanai/organization/1/website"><img src="https://opencollective.com/wangkanai/organization/1/avatar.svg"></a> <a href="https://opencollective.com/wangkanai/organization/2/website"><img src="https://opencollective.com/wangkanai/organization/2/avatar.svg"></a> <a href="https://opencollective.com/wangkanai/organization/3/website"><img src="https://opencollective.com/wangkanai/organization/3/avatar.svg"></a> <a href="https://opencollective.com/wangkanai/organization/4/website"><img src="https://opencollective.com/wangkanai/organization/4/avatar.svg"></a> <a href="https://opencollective.com/wangkanai/organization/5/website"><img src="https://opencollective.com/wangkanai/organization/5/avatar.svg"></a> <a href="https://opencollective.com/wangkanai/organization/6/website"><img src="https://opencollective.com/wangkanai/organization/6/avatar.svg"></a> <a href="https://opencollective.com/wangkanai/organization/7/website"><img src="https://opencollective.com/wangkanai/organization/7/avatar.svg"></a> <a href="https://opencollective.com/wangkanai/organization/8/website"><img src="https://opencollective.com/wangkanai/organization/8/avatar.svg"></a> <a href="https://opencollective.com/wangkanai/organization/9/website"><img src="https://opencollective.com/wangkanai/organization/9/avatar.svg"></a>

Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp3.1 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (13)

Showing the top 5 NuGet packages that depend on Wangkanai.Detection:

Package Downloads
WebVella.Erp.Web

The web components library for the open-source and free platform WebVella ERP. It allows a quick and painless creation of business web applications.

Wangkanai.Responsive

ASP.NET Core 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.

Wangkanai.Analytics

Embrace the power of data with Analytics, a .NET Core library for comprehensive website tracking. Delve into insightful statistics, understand your audience better, and make data-driven decisions with ease. From session duration to bounce rate, Analytics transforms raw data into meaningful insights. Join our community, shine a light on your website's performance, and let's unlock the full potential of website analytics with Analytics.

ZC.Middleware.DefaultAPI

Package Description

Wangkanai.Webmaster

Revolutionize your SEO with Wangkanai Webmaster. This ASP.NET Core tool boosts your site's traffic and visibility. Ideal for developers aiming to elevate their site's SEO. A must-have for enhanced web traffic, visibility, and efficiency

GitHub repositories (6)

Showing the top 5 popular GitHub repositories that depend on Wangkanai.Detection:

Repository Stars
dodyg/practical-aspnetcore
Practical samples of ASP.NET Core 9, 8.0, 7.0, 6.0, 5.0, 3.1, 2.2, and 2.1,projects you can use. Readme contains explanations on all projects.
grandnode/grandnode
Open source, headless, multi-tenant eCommerce platform built with .NET Core, MongoDB, AWS DocumentDB, Azure CosmosDB, Vue.js.
WebVella/WebVella-ERP
Free and open-source pluggable ERP and CRM software based on ASP.NET Core 8, RazorPages and PostgreSQL . Targets Linux or Windows as host OS.
grandnode/grandnode2
Open-Source eCommerce Platform on .NET Core, MongoDB, AWS DocumentDB, Azure CosmosDB, LiteDB & Vue.js
mrellipse/toucan
Boilerplate template using Vue.js, TypeScript and .NET Core 2.1, based on SOLID design principles
Version Downloads Last updated
8.14.0 102,744 5/8/2024
8.13.0 5,499 4/27/2024
8.12.0 52,335 3/9/2024
8.11.0 85,235 11/27/2023
8.10.0 1,943 11/23/2023
8.9.0 11,935 11/17/2023
8.8.0 1,726 11/15/2023
8.7.0 8,560 11/1/2023
8.6.0 910 10/22/2023
8.5.0 665 10/6/2023
8.4.0 840 9/28/2023
8.3.0 787 9/21/2023
8.2.0 2,213 7/20/2023
8.1.0 25,840 7/1/2023
8.0.0 2,199 6/28/2023
7.4.0 141,864 6/16/2023
7.3.2 169,942 6/7/2023
7.3.1 1,727 6/7/2023
7.3.0 46,853 5/15/2023
7.2.0 3,073 5/11/2023
7.1.1 42,586 4/13/2023
7.1.0 16,364 4/3/2023
7.0.0 88,576 1/18/2023
6.11.4 51,854 1/17/2023
6.11.3 43,899 1/10/2023
6.11.2 5,299 1/3/2023
6.11.1 2,590 12/31/2022
6.11.0 10,071 12/27/2022
6.10.0 4,503 12/23/2022
6.9.0 36,508 11/30/2022
6.8.0 8,455 11/28/2022
6.7.0 1,435 11/27/2022
6.6.0 3,363 11/26/2022
6.5.0 1,321 11/26/2022
6.4.0 2,370 11/24/2022
6.3.0 1,542 11/24/2022
6.2.0 22,569 11/14/2022
6.1.0 20,911 11/9/2022
6.0.0 2,874 11/9/2022
5.7.3 46,882 10/16/2022
5.7.2 31,513 9/27/2022
5.7.1 47,088 9/19/2022
5.7.0 10,302 9/13/2022
5.6.0 2,008 9/13/2022
5.5.300 3,328 9/9/2022
5.5.200 141,440 8/23/2022
5.5.100 1,603 8/21/2022
5.4.0 981 8/20/2022
5.3.0 62,892 6/23/2022
5.2.1 76,914 5/2/2022
5.2.0 150,284 3/8/2022
5.1.0 52,092 3/6/2022
5.0.0 14,836 2/9/2022
5.0.0-alpha8 754 2/9/2022
5.0.0-alpha7 733 2/8/2022
5.0.0-alpha6 468 2/8/2022
5.0.0-alpha5 811 2/4/2022
5.0.0-alpha4 4,238 12/7/2021
5.0.0-alpha3 573 12/5/2021
5.0.0-alpha2 526 12/4/2021
5.0.0-alpha1 496 12/3/2021
4.0.0 209,046 12/2/2021
4.0.0-beta4 516 12/2/2021
4.0.0-beta3 5,604 7/30/2021
4.0.0-beta2 65,236 5/11/2021
4.0.0-Beta1 857 5/5/2021
3.0.0 413,007 12/20/2020
3.0.0-beta2 766 12/20/2020
3.0.0-beta1 7,336 11/22/2020
3.0.0-alpha14 19,169 10/19/2020
3.0.0-alpha13 2,977 10/12/2020
3.0.0-alpha12 1,185 10/3/2020
3.0.0-alpha11 2,726 9/25/2020
3.0.0-alpha10 38,101 5/18/2020
3.0.0-alpha09 70,000 2/18/2020
3.0.0-alpha08 850 2/14/2020
3.0.0-alpha07 3,736 2/6/2020
3.0.0-alpha06 1,441 2/3/2020
3.0.0-alpha05 2,108 1/27/2020
3.0.0-alpha04 756 1/27/2020
3.0.0-alpha03 766 1/26/2020
3.0.0-alpha02 808 1/18/2020
3.0.0-alpha01 1,678 1/14/2020
2.0.1 243,998 9/25/2020
2.0.0 209,234 12/29/2019