Device detection services for 51Degrees Pipeline

OnPremise/GettingStarted-Web/Startup.cs

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

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

This example requires a local data file. The free 'Lite' data file can be downloaded with the scripts in the data GitHub repository, which this repository includes at cxx/data. Fetch the submodules by running git submodule update --init --recursive, then run sh cxx/data/get-data-files.sh 51Degrees-LiteV4.1.hash from the repository root, which saves the file as cxx/data/device-detection/51Degrees-LiteV4.1.hash.

The Lite data file is only used for illustration, and has limited accuracy and capabilities. The Enterprise data file has every property. Contact us about a copy.

Required NuGet Dependencies:

Overview

The UseFiftyOne extension method is used to create a Pipeline instance from the configuration that is supplied. The AddFiftyOne extension method adds a middleware component that will intercept requests and perform device detection. The results will be stored in the HttpContext. The middleware will also handle setting response headers (e.g. Accept-CH for User-Agent Client Hints) and serving requests for client-side JavaScript and JSON resources.

services.AddFiftyOne(Configuration);
app.UseFiftyOne();

The results of detection can be accessed by adding a dependency on IFlowDataProvider. This can then be used to interrogate the data.

var flowData = _provider.GetFlowData();
var deviceData = flowData.Get<IDeviceData>();
var hardwareVendor = deviceData.HardwareVendor;

Results can also be accessed in client-side code by using the fod object. See the JavaScriptBuilderElementBuilder for details on available settings such as changing the fod name.

window.onload = function () {
fod.complete(function(data) {
var hardwareName = data.device.hardwarename;
alert(hardwareName.join(", "));
}
}

Configuration

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
// For a sample configuration file demonstrating all available options, see
// https://github.com/51Degrees/51degrees-dotnet/blob/main/examples/device-detection/sample-configuration.json
"PipelineOptions": {
"Elements": [
{
"BuilderName": "DeviceDetectionHashEngineBuilder",
"BuildParameters": {
"DataFile": "51Degrees-LiteV4.1.hash",
"CreateTempDataCopy": false,
"AutoUpdate": false,
"PerformanceProfile": "MaxPerformance",
"DataFileSystemWatcher": false,
"DataUpdateOnStartUp": false,
// Explicitly include just the properties used by the example.
// IsVisible and HasWebDriver are answered by the JavaScript held in
// IsVisibleJavaScript and HasWebDriverJavaScript, so both halves of
// each pair have to be listed here or the browser is never asked.
// IsHeadless is read from the User-Agent and needs no JavaScript.
// These three are only in the Enterprise and TAC data files.
"Properties": "DeviceId,JavascriptHardwareProfile,HardwareVendor,HardwareModel,HardwareName,IsMobile,JavascriptGetHighEntropyValues,Promise,Fetch,DeviceType,PlatformVendor,PlatformName,PlatformVersion,BrowserVendor,BrowserName,BrowserVersion,ScreenPixelsWidth,ScreenPixelsHeight,ScreenPixelsWidthJavascript,ScreenPixelsHeightJavascript,CrawlerName,PriceBand,IsHeadless,IsVisible,IsVisibleJavaScript,HasWebDriver,HasWebDriverJavaScript"
}
},
{
// Required to add Javascript and JSON end points for 51Degrees.core.js and
"BuilderName": "JavaScriptBuilderElement",
"BuildParameters": {
"Minify": true
}
}
],
// Both these options default to true anyway.
// They are specified here for illustrative purposes.
"ClientSideEvidenceEnabled": true,
"UseAsyncScript": true,
"BuildParameters": {
//Suppress and log exceptions thrown from within (Web)Pipeline.Process().
//Set to `true` here so a device-detection failure degrades gracefully instead of
//returning a 500 for every request. Use `false` while developing to surface mistakes loudly.
"SuppressProcessExceptions": true
}
}
}

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;
using Microsoft.Extensions.Logging;
{
public class HomeController : Controller
{
private static bool _checkedDataFile = false;
private IFlowDataProvider _provider;
private ILogger<HomeController> _logger;
// The controller has a dependency on IFlowDataProvider. This is used to access the
// IFlowData that contains the device detection results for the current HTTP request.
public HomeController(IFlowDataProvider provider, ILogger<HomeController> logger)
{
_provider = provider;
_logger = logger;
}
public IActionResult Index()
{
// Log a warning if the data file is too old.
if(_checkedDataFile == false)
{
ExampleUtils.CheckDataFile(_provider.GetFlowData().Pipeline, _logger);
_checkedDataFile = true;
}
// Use the provider to get the flow data. This contains the results of device
// detection that has been performed by the pipeline.
return View(new IndexModel(_provider.GetFlowData(), Response.Headers));
}
}
}
static void CheckDataFile(IPipeline pipeline, ILogger logger)
Display information about the data file and log warnings if specific requirements are not met.
Definition ExampleUtils.cs:618
Definition OnPremise/GettingStarted-Web/Model/IndexModel.cs:34
Definition OnPremise/GettingStarted-Web/Controllers/HomeController.cs:29
Definition OnPremise/GettingStarted-Web/Model/EvidenceModel.cs:24

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.
* ********************************************************************* *@
@using FiftyOne.DeviceDetection.Examples
@model FiftyOne.DeviceDetection.Examples.OnPremise.GettingStartedWeb.Model.IndexModel
@{
ViewData["Title"] = "Web Integration Example";
}
<link rel="stylesheet" href="~/css/examples-main.min.css" />
<div class="c-eg-page">
@if (DateTime.UtcNow > Model.DataFile.DataPublishedDateTime.AddDays(ExampleUtils.DataFileAgeWarning))
{
<div class="c-eg-alert">
WARNING: This example is using a data file that is more than @ExampleUtils.DataFileAgeWarning
days old. A more recent data file may be needed to correctly detect the latest devices,
browsers, etc. The latest lite data file is downloaded by the scripts in the
<a href="https://github.com/51Degrees/data">data</a>
repository on GitHub. <a href="/contact-us?utm_source=code&amp;utm_medium=example&amp;utm_campaign=51degrees-dotnet&amp;utm_content=examples-onpremise-gettingstarted-web-views-home-index.cshtml&amp;utm_term=data-file-age-warning">Contact us</a>
about the Enterprise data file, which includes automatic daily updates.
</div>
}
<h2 class="c-eg-page__title">Web Integration Example OnPremise</h2>
<p class="c-eg-page__lead">
This example demonstrates the use of the Pipeline API to perform device detection within a
simple ASP.NET Core web project. It highlights automatic handling of the Accept-CH header,
used to request User-Agent Client Hints from the browser, and client-side evidence collection
to identify Apple device models and properties such as screen size.
</p>
<noscript>
<div class="c-eg-alert">
WARNING: JavaScript is disabled in your browser. This means that the callback discussed
further down this page will not fire and UACH headers will not be sent.
</div>
</noscript>
<div id="content">
<h3 class="c-eg-page__heading">Detection results</h3>
<p class="c-eg-page__lead">
The following values are determined by server-side device detection on the first request.
</p>
<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">@Model.HardwareVendor</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">@Model.HardwareName</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">@Model.DeviceType</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">@Model.PlatformVendor</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">@Model.PlatformName</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">@Model.PlatformVersion</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">@Model.BrowserVendor</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">@Model.BrowserName</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">@Model.BrowserVersion</td></tr>
<tr class="c-eg-table__row"><td class="c-eg-table__cell c-eg-table__cell--key">Screen width (pixels):</td><td class="c-eg-table__cell">@Model.ScreenWidth</td></tr>
<tr class="c-eg-table__row c-eg-table__row--alt"><td class="c-eg-table__cell c-eg-table__cell--key">Screen height (pixels):</td><td class="c-eg-table__cell">@Model.ScreenHeight</td></tr>
<tr class="c-eg-table__row"><td class="c-eg-table__cell c-eg-table__cell--key">Device Id:</td><td class="c-eg-table__cell">@Model.DeviceId</td></tr>
<tr class="c-eg-table__row c-eg-table__row--alt"><td class="c-eg-table__cell c-eg-table__cell--key">Price Band:</td><td class="c-eg-table__cell">@Model.PriceBand</td></tr>
<tr class="c-eg-table__row"><td class="c-eg-table__cell c-eg-table__cell--key">Headless browser:</td><td class="c-eg-table__cell" id="IsHeadless">@Model.IsHeadless</td></tr>
<tr class="c-eg-table__row c-eg-table__row--alt"><td class="c-eg-table__cell c-eg-table__cell--key">Has web driver:</td><td class="c-eg-table__cell" id="HasWebDriver">@Model.HasWebDriver</td></tr>
<tr class="c-eg-table__row"><td class="c-eg-table__cell c-eg-table__cell--key">Window visible:</td><td class="c-eg-table__cell" id="IsVisible">@Model.IsVisible</td></tr>
</tbody>
</table>
<h3 class="c-eg-page__heading">Evidence used</h3>
<p class="c-eg-legend">
Evidence was
<span class="c-eg-legend__swatch c-eg-legend__swatch--used">used</span>
/
<span class="c-eg-legend__swatch c-eg-legend__swatch--present">present</span>
for detection
</p>
<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.Evidence)
{
<tr class="c-eg-table__row @(entry.Used ? "c-eg-table__row--used" : "c-eg-table__row--present")">
<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>
<h3 class="c-eg-page__heading">Response headers</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.ResponseHeaders)
{
<tr class="c-eg-table__row c-eg-table__row--present">
<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>
@if (Model.ResponseHeaders.ContainsKey("Accept-CH") == false)
{
<div class="c-eg-alert">
WARNING: There is no Accept-CH header in the response. This may indicate that your
browser does not support User-Agent Client Hints. This is not necessarily a problem,
but if you want to try detection using User-Agent Client Hints, make sure your browser
<a href="https://developer.mozilla.org/en-US/docs/Web/API/User-Agent_Client_Hints_API#browser_compatibility">supports them</a>.
</div>
}
<h3 class="c-eg-page__heading">Client-side evidence and Apple models</h3>
<p class="c-eg-page__lead">
The information below is determined after a callback to the server with additional evidence
gathered by JavaScript on the client. The callback also includes any additional client hints
headers that have been requested. For Apple devices the server cannot tell the exact model,
so the callback shows a smaller set of possible models than the first request.
</p>
</div>
@if (Model.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-onpremise-gettingstarted-web-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-onpremise-gettingstarted-web-views-home-index.cshtml&amp;utm_term=paid-data-file">Contact us</a>
</div>
}
@* Kept outside #content, which the client-side results are appended to,
so this section stays at the end of the page. *@
<div class="c-eg-section" id="find-out-more">
<hr />
<h3 class="c-eg-page__heading">Find out more</h3>
<ul>
<li><a href="/documentation/_device_detection__overview.html?utm_source=code&amp;utm_medium=example&amp;utm_campaign=51degrees-dotnet&amp;utm_content=examples-onpremise-gettingstarted-web-views-home-index.cshtml&amp;utm_term=find-out-more">How device detection works</a></li>
<li><a href="/pricing?utm_source=code&amp;utm_medium=example&amp;utm_campaign=51degrees-dotnet&amp;utm_content=examples-onpremise-gettingstarted-web-views-home-index.cshtml&amp;utm_term=find-out-more">Data files and prices</a></li>
<li><a href="/contact-us?utm_source=code&amp;utm_medium=example&amp;utm_campaign=51degrees-dotnet&amp;utm_content=examples-onpremise-gettingstarted-web-views-home-index.cshtml&amp;utm_term=find-out-more">Talk to 51Degrees about using it</a></li>
</ul>
<p class="c-eg-page__lead">The source code for this demo and what it uses.</p>
<ul>
<li><a href="https://github.com/51Degrees/51degrees-dotnet/tree/main/examples/device-detection">https://github.com/51Degrees/51degrees-dotnet/tree/main/examples/device-detection</a></li>
<li><a href="https://github.com/51Degrees/51degrees-dotnet/tree/main/device-detection">https://github.com/51Degrees/51degrees-dotnet/tree/main/device-detection</a></li>
<li><a href="https://github.com/51Degrees/51degrees-cxx">https://github.com/51Degrees/51degrees-cxx</a></li>
<li><a href="https://github.com/51Degrees/51degrees-dotnet/tree/main/pipeline">https://github.com/51Degrees/51degrees-dotnet/tree/main/pipeline</a></li>
</ul>
</div>
</div>
@* The FiftyOneJS view component (from the FiftyOne.Pipeline.Web package) injects
51Degrees.core.js. That script sends client-side evidence back to the server and
raises the 'complete' event with the refined flow data. The shared examples.js
helper subscribes to it and appends a results table into #content. *@
@await Component.InvokeAsync("FiftyOneJS")
<script src="~/js/examples.min.js"></script>
<script>
window.onload = function () {
fodExamples.bindDeviceCallback({ targetId: "content" });
};
</script>

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 Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;
{
public class Startup
{
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)
{
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();
// Add the hash engine builder to services so that the system can find the builder
// when it needs to.
services.AddSingleton<DeviceDetectionHashEngineBuilder>();
// Configure the services needed by device detection and create the 51Degrees Pipeline
// instance that will be used to process requests.
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.UseDeveloperExceptionPage();
// This is only needed when running under an ASP.NET test server.
app.UseMiddleware<UserAgentCorrectionMiddleware>();
// Add the 51Degrees middleware component.
// This will pass any incoming requests through the pipeline API, performing device
// detection. The IFlowData that is used will be stored in the data associated with
// the current HTTP session.
// The IFlowDataAccessor provides an easy way to retrieve this data. See HomeController
// for an example of this.
app.UseFiftyOne();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
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);
}
}
}
}
Definition OnPremise/GettingStarted-Web/Startup.cs:92
Complete builder implementation for creating on premise DeviceDetectionHashEngine engines.
Definition DeviceDetectionHashEngineBuilder.cs:38
Definition OnPremise/GettingStarted-Web/Controllers/HomeController.cs:29
Definition DeviceDetectionHashEngine.cs:39