Raymond Raymond / ASP.NET Core

ASP.NET Core - Detect Browser and Device Type

event 2022-08-09 visibility 10,193 comment 0 insights toc
insights Stats

In modern web applications, we usually build responsive UI to work with different device and browser types. This makes the same set of code works well for both mobile and desktop browsers. However, under certain circumstances, it might be still useful to know the whether the request is sent from a mobile phone so that you can provide different responses accordingly. You can potentially uses it to see if the request is originated from a Bot agent, for example Google crawler.

About user agent

Each browser (regardless in mobile or desktop) adds a request header named User-Agent for each request. This request header is a string that lets servers and network peers identify the application, operating system, vendor, and/or version of the requesting user agent (credit User-Agent - HTTP | MDN).

For example, the following string is sent by my web browser:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.81 Safari/537.36 Edg/104.0.1293.47

From the content, the servers can know my browser is Edge on Windows 10.

Thus we could potentially use User-Agent request header to detect the browser and device types.

Is it a good idea?

As User-Agent is sent by client, there is no way to tell whether exactly whether it is authentic or not. Thus it is usually considered as a bad idea to equip user agent sniffing in web projects. For more details about things you need to consider before utilizing this approach, read more here: Browser detection using the user agent - HTTP | MDN.

If accuracy is not very critical and you have no other approaches to implement, the following section shows you how use do that using user agent request header.

So many user agents

There are many types and versions of user agents in the market. It is very hard to enumerate all of them. Instead of doing it by ourselves, we can utilizes some open source library.

One of the library comes to my mind is Wangkanai.Detection. It is available on GitHub:

wangkanai/Detection at main ยท wangkanai/wangkanai
warning As mentioned above, the result might not be accurate.

Use detection service

The link above already provides much information about how to install this package and then use it.

Install the package

Depends on your toolchain, you can choose the suitable approach to add this package into your project:

NuGet Gallery | Wangkanai.Detection 5.3.0

For example, we can use the following command line to add it through dotnet CLI:

dotnet add package Wangkanai.Detection --version 5.3.0

Register and use the services

Now we need to register the services in DI (dependency injection) and then use it. Typically we can add them in Startup.cs (or in equivalent functions if you are not using Startup.cs).

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

public void Configure(IApplicationBuilder app, IHostingEnvironment env)

If you want to use different layouts in Razor Pages for mobile agents, you need to ensure UseDetection() is added before UseRouting().

Use IDetectionService

If you only want to use the detection service in your code without advanced features, please directly use IDetectionService in your controller or Razor Pages model. This service is already registered in service.

The following sections provide some examples. 

Razor Pages example

@inject Wangkanai.Detection.Services.IDetectionService DetectionService
    ViewData["Title"] = "Detection";

API Controller example

public class MyController : ControllerBase
    private readonly IDetectionService detectionService;

    public MyController(IDetectionService detectionService)
        detectionService = detectionService;

    public IActionResult GetUser()
		if(detectionService.Device.Type == Device.Mobile)
			return new JsonResult(detectionService.Device);
			return NotFound();

The above code snippet only returns JSON result if the device type is mobile.

Other libraries

There are also other packages that can be used that provide similar functionality. For example, DeviceDetector.NET is one of them though is has not been updated for about one year now. 

I hope this article is useful to you. If you have any question, feel free to comment if you have any questions.

More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts