Device detection services for 51Degrees Pipeline

UACH/Startup.cs

This example demonstrates device detection using User-Agent Client Hints on a website.

This example demonstrates device detection using User-Agent Client Hints on a website. When a browser that supports User-Agent Client Hints first visits a website, the server receives the sec-ch-ua and sec-ch-ua-mobile headers along with the user-agent header. The server uses these headers to determine whether the browser supports User-Agent Client Hints. It can request additional hints by setting the Accept-CH response header. Clicking the button below will cause a new request to be sent to the server, along with any additional headers that have been requested.

The source code for this example is available in full on GitHub.

Required NuGet Dependencies:

  1. Add Pipeline configuration options to appsettings.json. (or a separate file if you prefer. Just don't forget to add that file to your startup.cs)
    {
    "PipelineOptions": {
    "Elements": [
    {
    "BuilderName": "DeviceDetectionHashEngineBuilder",
    "BuildParameters": {
    "DataFile": "51Degrees-LiteV4.1.hash",
    "CreateTempDataCopy": false,
    "AutoUpdate": false,
    "PerformanceProfile": "MaxPerformance",
    "DataFileSystemWatcher": false,
    "DataUpdateOnStartUp": false
    }
    }
    ]
    }
    }
  2. Add builders and the Pipeline to the server's services.
    public class Startup
    {
    ...
    public void ConfigureServices(IServiceCollection services)
    {
    ...
    services.AddSingleton<DeviceDetectionHashEngineBuilder>();
    services.AddFiftyOne(Configuration);
    ...
  3. Configure the server to use the Pipeline which has just been set up.
    public class Startup
    {
    ...
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
    app.UseFiftyOne();
    ...
  4. Inject the IFlowDataProvider into a controller.
    public class HomeController : Controller
    {
    private IFlowDataProvider _flow;
    public HomeController(IFlowDataProvider flow)
    {
    _flow = flow;
    }
    ...
    }
  5. Pass the results contained in the flow data to the view.
    public class HomeController : Controller
    {
    ...
    public IActionResult Index()
    {
    var data = _flow.GetFlowData().Get<IDeviceData>();
    return View(data);
    }
    ...
  6. Display device details in the view.
    @model FiftyOne.DeviceDetection.IDeviceData
    ...
    var hardwareVendor = Model.HardwareVendor;
    ...
    Hardware Vendor: @(hardwareVendor.HasValue ? hardwareVendor.Value : $"Unknown ({hardwareVendor.NoValueMessage})")<br />
    ...

Controller

/* *********************************************************************
* This Original Work is copyright of 51 Degrees Mobile Experts Limited.
* Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House,
* Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU.
*
* This Original Work is licensed under the European Union Public Licence
* (EUPL) v.1.2 and is subject to its terms as set out below.
*
* If a copy of the EUPL was not distributed with this file, You can obtain
* one at https://opensource.org/licenses/EUPL-1.2.
*
* The 'Compatible Licences' set out in the Appendix to the EUPL (as may be
* amended by the European Commission) shall be deemed incompatible for
* the purposes of the Work and the provisions of the compatibility
* clause in Article 5 of the EUPL shall not apply.
*
* If using the Work as, or as part of, a network application, by
* including the attribution notice(s) required under Article 5 of the EUPL
* in the end user terms of the application under an appropriate heading,
* such notice(s) shall fulfill the requirements of that article.
* ********************************************************************* */
using Microsoft.AspNetCore.Mvc;
{
public class HomeController : Controller
{
private IFlowDataProvider _flow;
public HomeController(IFlowDataProvider flow)
{
_flow = flow;
}
public IActionResult Index()
{
return View(_flow.GetFlowData());
}
}
}
Definition Legacy Web/UACH/Controllers/HomeController.cs:27

View

@* *********************************************************************
* This Original Work is copyright of 51 Degrees Mobile Experts Limited.
* Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House,
* Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU.
*
* This Original Work is licensed under the European Union Public Licence
* (EUPL) v.1.2 and is subject to its terms as set out below.
*
* If a copy of the EUPL was not distributed with this file, You can obtain
* one at https://opensource.org/licenses/EUPL-1.2.
*
* The 'Compatible Licences' set out in the Appendix to the EUPL (as may be
* amended by the European Commission) shall be deemed incompatible for
* the purposes of the Work and the provisions of the compatibility
* clause in Article 5 of the EUPL shall not apply.
*
* If using the Work as, or as part of, a network application, by
* including the attribution notice(s) required under Article 5 of the EUPL
* in the end user terms of the application under an appropriate heading,
* such notice(s) shall fulfill the requirements of that article.
* ********************************************************************* *@
@model FiftyOne.Pipeline.Core.Data.IFlowData
@{
ViewData["Title"] = "User Agent Client Hints Example";
var deviceData = Model.Get<FiftyOne.DeviceDetection.IDeviceData>();
var hardwareVendor = deviceData.HardwareVendor;
var hardwareName = deviceData.HardwareName;
var deviceType = deviceData.DeviceType;
var platformVendor = deviceData.PlatformVendor;
var platformName = deviceData.PlatformName;
var platformVersion = deviceData.PlatformVersion;
var browserVendor = deviceData.BrowserVendor;
var browserName = deviceData.BrowserName;
var browserVersion = deviceData.BrowserVersion;
var engine = Model.Pipeline.GetElement<FiftyOne.DeviceDetection.Hash.Engine.OnPremise.FlowElements.DeviceDetectionHashEngine>();
}
<link rel="stylesheet" href="~/css/examples-main.min.css" />
<div class="c-eg-page">
<h2 class="c-eg-page__title">User Agent Client Hints Example</h2>
<p class="c-eg-page__lead">
By default, the user-agent, sec-ch-ua and sec-ch-ua-mobile HTTP headers
are sent.
<br />
This means that on the first request, the server can determine the
browser from sec-ch-ua while other details must be derived from the
user-agent.
<br />
If the server determines that the browser supports client hints, then
it may request additional client hints headers by setting the
Accept-CH header in the response.
<br />
Select the <strong>Make second request</strong> button below,
to use send another request to the server. This time, any
additional client hints headers that have been requested
will be included.
</p>
<button type="button" class="b-btn" onclick="redirect()">Make second request</button>
<script>
// This script will run when button will be clicked and device detection request will again
// be sent to the server with all additional client hints that was requested in the previous
// response by the server.
// Following sequence will be followed.
// 1. User will send the first request to the web server for detection.
// 2. Web Server will return the properties in response based on the headers sent in the request. Along
// with the properties, it will also send a new header field Accept-CH in response indicating the additional
// evidence it needs. It builds the new response header using SetHeader[Component name]Accept-CH properties
// where Component Name is the name of the component for which properties are required.
// 3. When "Use User Agent Client Hints" button will be clicked, device detection request will again
// be sent to the server with all additional client hints that was requested in the previous
// response by the server.
// 4. Web Server will return the properties based on the new User Agent Client Hint headers
// being used as evidence.
function redirect() {
sessionStorage.reloadAfterPageLoad = true;
window.location.reload(true);
}
window.onload = function () {
if (sessionStorage.reloadAfterPageLoad) {
document.getElementById('description').innerHTML = "<p>The information shown below is determined using <strong>User Agent Client Hints</strong> that was sent in the request to obtain additional evidence. If no additional evidence appears in the table above, then it may indicate an external problem such as <strong>User Agent Client Hints</strong> being disabled or unsupported by your browser.</p>";
sessionStorage.reloadAfterPageLoad = false;
}
else {
document.getElementById('description').innerHTML = "<p>The following values are determined by sever-side device detection on the first request.</p>";
}
}
</script>
<div id="evidence">
<h3 class="c-eg-page__heading">Evidence values used</h3>
<table class="c-eg-table">
<thead class="c-eg-table__head">
<tr class="c-eg-table__row">
<th class="c-eg-table__cell">Key</th>
<th class="c-eg-table__cell">Value</th>
</tr>
</thead>
<tbody>
@foreach (var entry in Model.GetEvidence().AsDictionary()
.Where(e => engine.EvidenceKeyFilter.Include(e.Key)))
{
<tr class="c-eg-table__row c-eg-table__row--used">
<td class="c-eg-table__cell c-eg-table__cell--key">@(entry.Key)</td>
<td class="c-eg-table__cell">@(entry.Value)</td>
</tr>
}
</tbody>
</table>
</div>
<div id="description"></div>
<div id="content">
<h3 class="c-eg-page__heading">Detection results</h3>
<table class="c-eg-table">
<thead class="c-eg-table__head">
<tr class="c-eg-table__row">
<th class="c-eg-table__cell">Key</th>
<th class="c-eg-table__cell">Value</th>
</tr>
</thead>
<tbody>
<tr class="c-eg-table__row c-eg-table__row--alt"><td class="c-eg-table__cell c-eg-table__cell--key">Hardware Vendor:</td><td class="c-eg-table__cell">@(hardwareVendor.HasValue ? hardwareVendor.Value : $"Unknown ({hardwareVendor.NoValueMessage})")</td></tr>
<tr class="c-eg-table__row"><td class="c-eg-table__cell c-eg-table__cell--key">Hardware Name:</td><td class="c-eg-table__cell">@(hardwareName.HasValue ? string.Join(", ", hardwareName.Value) : $"Unknown ({hardwareName.NoValueMessage})")</td></tr>
<tr class="c-eg-table__row c-eg-table__row--alt"><td class="c-eg-table__cell c-eg-table__cell--key">Device Type:</td><td class="c-eg-table__cell">@(deviceType.HasValue ? deviceType.Value : $"Unknown ({deviceType.NoValueMessage})")</td></tr>
<tr class="c-eg-table__row"><td class="c-eg-table__cell c-eg-table__cell--key">Platform Vendor:</td><td class="c-eg-table__cell">@(platformVendor.HasValue ? platformVendor.Value : $"Unknown ({platformVendor.NoValueMessage})")</td></tr>
<tr class="c-eg-table__row c-eg-table__row--alt"><td class="c-eg-table__cell c-eg-table__cell--key">Platform Name:</td><td class="c-eg-table__cell">@(platformName.HasValue ? platformName.Value : $"Unknown ({platformName.NoValueMessage})")</td></tr>
<tr class="c-eg-table__row"><td class="c-eg-table__cell c-eg-table__cell--key">Platform Version:</td><td class="c-eg-table__cell">@(platformVersion.HasValue ? platformVersion.Value : $"Unknown ({platformVersion.NoValueMessage})")</td></tr>
<tr class="c-eg-table__row c-eg-table__row--alt"><td class="c-eg-table__cell c-eg-table__cell--key">Browser Vendor:</td><td class="c-eg-table__cell">@(browserVendor.HasValue ? browserVendor.Value : $"Unknown ({browserVendor.NoValueMessage})")</td></tr>
<tr class="c-eg-table__row"><td class="c-eg-table__cell c-eg-table__cell--key">Browser Name:</td><td class="c-eg-table__cell">@(browserName.HasValue ? browserName.Value : $"Unknown ({browserName.NoValueMessage})")</td></tr>
<tr class="c-eg-table__row c-eg-table__row--alt"><td class="c-eg-table__cell c-eg-table__cell--key">Browser Version:</td><td class="c-eg-table__cell">@(browserVersion.HasValue ? browserVersion.Value : $"Unknown ({browserVersion.NoValueMessage})")</td></tr>
</tbody>
</table>
</div>
@if (engine.DataSourceTier == "Lite")
{
<div class="c-eg-message">
<p class="c-eg-message__text">The paid data file adds daily automatic updates, non-human identification and IP intelligence. <a href="/contact-us?utm_source=code&amp;utm_medium=example&amp;utm_campaign=51degrees-dotnet&amp;utm_content=examples-legacy-web-uach-views-home-index.cshtml&amp;utm_term=paid-data-file">Contact us</a> to explore the options.</p>
<a class="b-btn c-eg-message__cta" href="/contact-us?utm_source=code&amp;utm_medium=example&amp;utm_campaign=51degrees-dotnet&amp;utm_content=examples-legacy-web-uach-views-home-index.cshtml&amp;utm_term=paid-data-file">Contact us</a>
</div>
}
</div>

Startup

/* *********************************************************************
* This Original Work is copyright of 51 Degrees Mobile Experts Limited.
* Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House,
* Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU.
*
* This Original Work is licensed under the European Union Public Licence
* (EUPL) v.1.2 and is subject to its terms as set out below.
*
* If a copy of the EUPL was not distributed with this file, You can obtain
* one at https://opensource.org/licenses/EUPL-1.2.
*
* The 'Compatible Licences' set out in the Appendix to the EUPL (as may be
* amended by the European Commission) shall be deemed incompatible for
* the purposes of the Work and the provisions of the compatibility
* clause in Article 5 of the EUPL shall not apply.
*
* If using the Work as, or as part of, a network application, by
* including the attribution notice(s) required under Article 5 of the EUPL
* in the end user terms of the application under an appropriate heading,
* such notice(s) shall fulfill the requirements of that article.
* ********************************************************************* */
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Client_Hints
{
public class Startup
{
private class UserAgentCorrectionMiddleware
{
private readonly RequestDelegate next;
public UserAgentCorrectionMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext httpContext)
{
var val = httpContext.Request.Headers["User-Agent"];
httpContext.Request.Headers.Remove("User-Agent");
httpContext.Request.Headers["User-Agent"] = new Microsoft.Extensions.Primitives.StringValues(string.Join(" ", val));
await this.next(httpContext);
}
}
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// This section is not generally necessary. We're just checking
// if the resource key has been set to a new value so we can
// warn the user if it has not.
// --------------------------------------------------------------
var options = new PipelineOptions();
var section = Configuration.GetRequiredSection("PipelineOptions");
// Use the 'ErrorOnUnknownConfiguration' option to warn us if we've got any
// misnamed configuration keys.
section.Bind(options, (o) => { o.ErrorOnUnknownConfiguration = true; });
var engineConfig = options.Elements.Where(e =>
e.BuilderName.Contains(nameof(DeviceDetectionHashEngine),
StringComparison.OrdinalIgnoreCase));
if (engineConfig.Count() > 0)
{
object dataFile = null;
if (engineConfig.Any(c => c.BuildParameters
.TryGetValue("DataFile", out dataFile) == true))
{
var dataFileStr = dataFile.ToString();
string dataFilePath =
Path.IsPathRooted(dataFileStr) ?
dataFileStr :
Path.Combine(Environment.CurrentDirectory, dataFileStr);
if (File.Exists(dataFilePath) == false)
{
throw new Exception($"No data file found at " +
$"'{dataFilePath}'. This location can be set " +
$"using the 'DataFile' entry in the " +
$"appsettings.json file. Also, note that the " +
$"free 'lite' data file is insufficient to run " +
$"this example. A paid-for file can be obtained " +
$"from /pricing?utm_source=code&utm_medium=example&utm_campaign=51degrees-dotnet&utm_content=examples-legacy-web-uach-startup.cs&utm_term=data-file-required.");
}
}
}
// --------------------------------------------------------------
services.AddControllersWithViews();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc();
services.AddSingleton<DeviceDetectionHashEngineBuilder>();
services.AddFiftyOne(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
app.UseMiddleware<UserAgentCorrectionMiddleware>();
app.UseFiftyOne();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Complete builder implementation for creating on premise DeviceDetectionHashEngine engines.
Definition DeviceDetectionHashEngineBuilder.cs:38
Hash device detection engine.
Definition DeviceDetectionHashEngine.cs:48
Definition Legacy Web/UACH/Controllers/HomeController.cs:27
Definition DeviceDetectionHashEngine.cs:39