Table of Contents

UserAgentSentinelFilter Class

Definition

A filter that provides an User-Agent sentinel on action methods.

public class UserAgentSentinelFilter : ConfigurableAsyncActionFilter<UserAgentSentinelOptions>, IConfigurable<UserAgentSentinelOptions>, IAsyncActionFilter, IFilterMetadata
Inheritance
UserAgentSentinelFilter
Implements
Inherited Members

Examples

The following example configures to require and validate a known User-Agent header, then invokes OnActionExecutionAsync for both a missing header and an allowed header.

// Program.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Cuemon.AspNetCore.Http.Headers;
using Cuemon.AspNetCore.Mvc.Filters.Headers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Options;

var options = Options.Create(new UserAgentSentinelOptions
{
    RequireUserAgentHeader = true,
    ValidateUserAgentHeader = true
});
options.Value.AllowedUserAgents.Add("Cuemon-Agent");

var filter = new UserAgentSentinelFilter(options);

var missingContext = new ActionExecutingContext(
    new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()),
    new List<IFilterMetadata>(),
    new Dictionary<string, object>(),
    new object());

try
{
    await filter.OnActionExecutionAsync(missingContext, () =>
        Task.FromResult(new ActionExecutedContext(missingContext, new List<IFilterMetadata>(), new object())));
}
catch (UserAgentException ex)
{
    Console.WriteLine($"Missing User-Agent rejected: {(int)ex.StatusCode} ({ex.ReasonPhrase})");
}

var allowedHttpContext = new DefaultHttpContext();
allowedHttpContext.Request.Headers.UserAgent = "Cuemon-Agent";
var allowedContext = new ActionExecutingContext(
    new ActionContext(allowedHttpContext, new RouteData(), new ActionDescriptor()),
    new List<IFilterMetadata>(),
    new Dictionary<string, object>(),
    new object());
bool nextCalled = false;
await filter.OnActionExecutionAsync(allowedContext, () =>
{
    nextCalled = true;
    return Task.FromResult(new ActionExecutedContext(allowedContext, new List<IFilterMetadata>(), new object()));
});
Console.WriteLine($"Allowed User-Agent proceeded to action: {nextCalled}");

Constructors

Name Description
UserAgentSentinelFilter(IOptions<UserAgentSentinelOptions>)

Initializes a new instance of the UserAgentSentinelFilter class.

Methods

Name Description
OnActionExecutionAsync(ActionExecutingContext, ActionExecutionDelegate)

Called asynchronously before the action, after model binding is complete.

See Also