Skip to content

w8tcha/uap-csharp

 
 

Repository files navigation

UserAgent Parser (based on ua_parser C# Library)

This is the ASP.NET Core implementation of ua-parser.

NuGet

build dotnet

The implementation uses the shared regex patterns and overrides from regexes.yaml (found in uap-core). The assembly embeds the latest regex patterns (enabled through a node module) which are loaded into the default parser. You can create a parser with more updated regex patterns by using the static methods on Parser to pass in specific patterns in yaml format.

Build and Run Tests


You can then build and run the tests by

> dotnet restore UAParser.Core.sln
> dotnet test UAParser.Core.sln

Update the embedded regexes

To pull the latest regexes into the project:

> npm install && grunt

How to use ?

Step 1: Install the UAParser.Core nuget package

> Install-Package UAParser.Core

Step 2: Enable the browser detection service inside the ConfigureServices method of Startup.cs.

public void ConfigureServices(IServiceCollection services)
{
    // Add user agent service
    services.AddUserAgentParser();

    services.AddMvc();
}

Step 3: Inject IUserAgentParser to your controller class or view file or middleware and access the ClientInfo property.

Example usage in controller code

public class HomeController : Controller
{
    private readonly IUserAgentParser userAgentParser;
    public HomeController(IUserAgentParser parser)
    {
        this.userAgentParser = parser;
    }
    public IActionResult Index()
    {
        var clientInfo = this.userAgentParser.ClientInfo;
        // Use ClientInfo object as needed.

        return View();
    }
}

Example usage in view code

@inject UAParser.Interfaces.IUserAgentParser parser

<h2> @parser.ClientInfo.Browser.Family </h2>
<h3> @parser.ClientInfo.Browser.Version </h3>
<h3> @parser.ClientInfo.OS.ToString() </h3>
<h3> @parser.ClientInfo.Device.ToString() </h3>

Example usage in custom middlware

You can inject the IUserAgentParser to the InvokeAsync method.

public class MyCustomMiddleware
{
    private RequestDelegate next;
    public MyCustomMiddleware(RequestDelegate next)
    {
        this.next = next;
    }
    public async Task InvokeAsync(HttpContext httpContext, IUserAgentParser parser)
    {
        var clientInfo = parser.ClientInfo;

        if (clientInfo.Browser.Family == "Edge")
        {
            await httpContext.Response.WriteAsync("Have you tried the new chromuim based edge ?");
        }
        else
        {
            await this.next.Invoke(httpContext);
        }
    }
}

Authors:

Releases

No releases published

Packages

No packages published

Languages

  • C# 73.7%
  • JavaScript 20.0%
  • HTML 4.8%
  • Perl 1.5%