Asp.Net Core Extended

Spread the love

Filters in ASP.NET Core

Filters in ASP.NET Core allow code to run before or after specific stages in the request processing pipeline.

Built-in filters handle tasks such as:

  • Authorization, preventing access to resources a user isn’t authorized for.
  • Response caching, short-circuiting the request pipeline to return a cached response.

Custom filters can be created to handle cross-cutting concerns. Examples of cross-cutting concerns include error handling, caching, configuration, authorization, and logging. Filters avoid duplicating code. For example, an error handling exception filter could consolidate error handling.

This document applies to Razor Pages, API controllers, and controllers with views. Filters don’t work directly with Razor components. A filter can only indirectly affect a component when:

  • The component is embedded in a page or view.
  • The page or controller and view uses the filter.

How filters work

Filters run within the ASP.NET Core action invocation pipeline, sometimes referred to as the filter pipeline. The filter pipeline runs after ASP.NET Core selects the action to execute:

Filter types

Each filter type is executed at a different stage in the filter pipeline:

  • Authorization filters:
    • Run first.
    • Determine whether the user is authorized for the request.
    • Short-circuit the pipeline if the request is not authorized.
  • Resource filters:
    • Run after authorization.
    • OnResourceExecuting runs code before the rest of the filter pipeline. For example, OnResourceExecuting runs code before model binding.
  • Action filters:
    • Run immediately before and after an action method is called.
    • Can change the arguments passed into an action.
    • Can change the result returned from the action.
    • Are not supported in Razor Pages.
  • Exception filters apply global policies to unhandled exceptions that occur before the response body has been written to.
  • Result filters:
    • Run immediately before and after the execution of action results.
    • Run only when the action method executes successfully.
    • Are useful for logic that must surround view or formatter execution.

The following diagram shows how filter types interact in the filter pipeline:

Razor Pages also support Razor Page filters, which run before and after a Razor Page handler.

Implementation

Filters support both synchronous and asynchronous implementations through different interface definitions.

Synchronous filters run before and after their pipeline stage. For example, OnActionExecuting is called before the action method is called. OnActionExecuted is called after the action method returns:

C#Copy

public class SampleActionFilter : IActionFilter

{

    public void OnActionExecuting(ActionExecutingContext context)

    {

        // Do something before the action executes.

    }

    public void OnActionExecuted(ActionExecutedContext context)

    {

        // Do something after the action executes.

    }

}

Asynchronous filters define an On-Stage-ExecutionAsync method. For example, OnActionExecutionAsync:

C#Copy

public class SampleAsyncActionFilter : IAsyncActionFilter

{

    public async Task OnActionExecutionAsync(

        ActionExecutingContext context, ActionExecutionDelegate next)

    {

        // Do something before the action executes.

        await next();

        // Do something after the action executes.

    }

}

In the preceding code, the SampleAsyncActionFilter has an ActionExecutionDelegate, next, which executes the action method.

Multiple filter stages

Interfaces for multiple filter stages can be implemented in a single class. For example, the ActionFilterAttribute class implements:

Implement either the synchronous or the async version of a filter interface, not both. The runtime checks first to see if the filter implements the async interface, and if so, it calls that. If not, it calls the synchronous interface’s method(s). If both asynchronous and synchronous interfaces are implemented in one class, only the async method is called. When using abstract classes like ActionFilterAttribute, override only the synchronous methods or the asynchronous methods for each filter type.

Built-in filter attributes

ASP.NET Core includes built-in attribute-based filters that can be subclassed and customized. For example, the following result filter adds a header to the response:

C#Copy

public class ResponseHeaderAttribute : ActionFilterAttribute

{

    private readonly string _name;

    private readonly string _value;

    public ResponseHeaderAttribute(string name, string value) =>

        (_name, _value) = (name, value);

    public override void OnResultExecuting(ResultExecutingContext context)

    {

        context.HttpContext.Response.Headers.Add(_name, _value);

        base.OnResultExecuting(context);

    }

}

Attributes allow filters to accept arguments, as shown in the preceding example. Apply the ResponseHeaderAttribute to a controller or action method and specify the name and value of the HTTP header:

C#Copy

[ResponseHeader(“Filter-Header”, “Filter Value”)]

public class ResponseHeaderController : ControllerBase

{

    public IActionResult Index() =>

        Content(“Examine the response headers using the F12 developer tools.”);

    // …

Use a tool such as the browser developer tools to examine the headers. Under Response Headers, filter-header: Filter Value is displayed.

The following code applies ResponseHeaderAttribute to both a controller and an action:

C#Copy

[ResponseHeader(“Filter-Header”, “Filter Value”)]

public class ResponseHeaderController : ControllerBase

{

    public IActionResult Index() =>

        Content(“Examine the response headers using the F12 developer tools.”);

    // …

    [ResponseHeader(“Another-Filter-Header”, “Another Filter Value”)]

    public IActionResult Multiple() =>

        Content(“Examine the response headers using the F12 developer tools.”);

}

Responses from the Multiple action include the following headers:

  • filter-header: Filter Value
  • another-filter-header: Another Filter Value

Several of the filter interfaces have corresponding attributes that can be used as base classes for custom implementations.

Filter attributes:

Filters cannot be applied to Razor Page handler methods. They can be applied either to the Razor Page model or globally.

Filter scopes and order of execution

A filter can be added to the pipeline at one of three scopes:

  • Using an attribute on a controller or Razor Page.
  • Using an attribute on a controller action. Filter attributes cannot be applied to Razor Pages handler methods.
  • Globally for all controllers, actions, and Razor Pages as shown in the following code:

C#Copy

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews(options =>

{

    options.Filters.Add<GlobalSampleActionFilter>();

});

Default order of execution

When there are multiple filters for a particular stage of the pipeline, scope determines the default order of filter execution. Global filters surround class filters, which in turn surround method filters.

As a result of filter nesting, the after code of filters runs in the reverse order of the before code. The filter sequence:

  • The before code of global filters.
    • The before code of controller filters.
      • The before code of action method filters.
      • The after code of action method filters.
    • The after code of controller filters.
  • The after code of global filters.

The following example illustrates the order in which filter methods run for synchronous action filters:

SequenceFilter scopeFilter method
1GlobalOnActionExecuting
2ControllerOnActionExecuting
3ActionOnActionExecuting
4ActionOnActionExecuted
5ControllerOnActionExecuted
6GlobalOnActionExecuted

Controller level filters

Every controller that inherits from Controller includes the OnActionExecutingOnActionExecutionAsync, and OnActionExecuted methods. These methods wrap the filters that run for a given action:

  • OnActionExecuting runs before any of the action’s filters.
  • OnActionExecuted runs after all of the action’s filters.
  • OnActionExecutionAsync runs before any of the action’s filters. Code after a call to next runs after the action’s filters.

The following ControllerFiltersController class:

  • Applies the SampleActionFilterAttribute ([SampleActionFilter]) to the controller.
  • Overrides OnActionExecuting and OnActionExecuted.

C#Copy

[SampleActionFilter]

public class ControllerFiltersController : Controller

{

    public override void OnActionExecuting(ActionExecutingContext context)

    {

        Console.WriteLine(

            $”- {nameof(ControllerFiltersController)}.{nameof(OnActionExecuting)}”);

        base.OnActionExecuting(context);

    }

    public override void OnActionExecuted(ActionExecutedContext context)

    {

        Console.WriteLine(

            $”- {nameof(ControllerFiltersController)}.{nameof(OnActionExecuted)}”);

        base.OnActionExecuted(context);

    }

    public IActionResult Index()

    {

        Console.WriteLine(

            $”- {nameof(ControllerFiltersController)}.{nameof(Index)}”);

        return Content(“Check the Console.”);

    }

}

Navigating to https://localhost:<port>/ControllerFilters runs the following code:

  • ControllerFiltersController.OnActionExecuting
    • GlobalSampleActionFilter.OnActionExecuting
      • SampleActionFilterAttribute.OnActionExecuting
        • ControllerFiltersController.Index
      • SampleActionFilterAttribute.OnActionExecuted
    • GlobalSampleActionFilter.OnActionExecuted
  • ControllerFiltersController.OnActionExecuted

Controller level filters set the Order property to int.MinValue. Controller level filters can not be set to run after filters applied to methods. Order is explained in the next section.

For Razor Pages, see Implement Razor Page filters by overriding filter methods.

Override the default order

The default sequence of execution can be overridden by implementing IOrderedFilter. IOrderedFilter exposes the Order property that takes precedence over scope to determine the order of execution. A filter with a lower Order value:

  • Runs the before code before that of a filter with a higher value of Order.
  • Runs the after code after that of a filter with a higher Order value.

In the Controller level filters example, GlobalSampleActionFilter has global scope so it runs before SampleActionFilterAttribute, which has controller scope. To make SampleActionFilterAttribute run first, set its order to int.MinValue:

C#Copy

[SampleActionFilter(Order = int.MinValue)]

public class ControllerFiltersController : Controller

{

    // …

}

To make the global filter GlobalSampleActionFilter run first, set its Order to int.MinValue:

C#Copy

builder.Services.AddControllersWithViews(options =>

{

    options.Filters.Add<GlobalSampleActionFilter>(int.MinValue);

});

Cancellation and short-circuiting

The filter pipeline can be short-circuited by setting the Result property on the ResourceExecutingContext parameter provided to the filter method. For example, the following Resource filter prevents the rest of the pipeline from executing:

C#Copy

public class ShortCircuitingResourceFilterAttribute : Attribute, IResourceFilter

{

    public void OnResourceExecuting(ResourceExecutingContext context)

    {

        context.Result = new ContentResult

        {

            Content = nameof(ShortCircuitingResourceFilterAttribute)

        };

    }

    public void OnResourceExecuted(ResourceExecutedContext context) { }

}

In the following code, both the [ShortCircuitingResourceFilter] and the [ResponseHeader] filter target the Index action method. The ShortCircuitingResourceFilterAttribute filter:

  • Runs first, because it’s a Resource Filter and ResponseHeaderAttribute is an Action Filter.
  • Short-circuits the rest of the pipeline.

Therefore the ResponseHeaderAttribute filter never runs for the Index action. This behavior would be the same if both filters were applied at the action method level, provided the ShortCircuitingResourceFilterAttribute ran first. The ShortCircuitingResourceFilterAttribute runs first because of its filter type:

C#Copy

[ResponseHeader(“Filter-Header”, “Filter Value”)]

public class ShortCircuitingController : Controller

{

    [ShortCircuitingResourceFilter]

    public IActionResult Index() =>

        Content($”- {nameof(ShortCircuitingController)}.{nameof(Index)}”);

}

Dependency injection

Filters can be added by type or by instance. If an instance is added, that instance is used for every request. If a type is added, it’s type-activated. A type-activated filter means:

  • An instance is created for each request.
  • Any constructor dependencies are populated by dependency injection (DI).

Filters that are implemented as attributes and added directly to controller classes or action methods cannot have constructor dependencies provided by dependency injection (DI). Constructor dependencies cannot be provided by DI because attributes must have their constructor parameters supplied where they’re applied.

The following filters support constructor dependencies provided from DI:

The preceding filters can be applied to a controller or an action.

Loggers are available from DI. However, avoid creating and using filters purely for logging purposes. The built-in framework logging typically provides what’s needed for logging. Logging added to filters:

  • Should focus on business domain concerns or behavior specific to the filter.
  • Should not log actions or other framework events. The built-in filters already log actions and framework events.

ServiceFilterAttribute

Service filter implementation types are registered in Program.cs. A ServiceFilterAttribute retrieves an instance of the filter from DI.

The following code shows the LoggingResponseHeaderFilterService class, which uses DI:

C#Copy

public class LoggingResponseHeaderFilterService : IResultFilter

{

    private readonly ILogger _logger;

    public LoggingResponseHeaderFilterService(

            ILogger<LoggingResponseHeaderFilterService> logger) =>

        _logger = logger;

    public void OnResultExecuting(ResultExecutingContext context)

    {

        _logger.LogInformation(

            $”- {nameof(LoggingResponseHeaderFilterService)}.{nameof(OnResultExecuting)}”);

        context.HttpContext.Response.Headers.Add(

            nameof(OnResultExecuting), nameof(LoggingResponseHeaderFilterService));

    }

    public void OnResultExecuted(ResultExecutedContext context)

    {

        _logger.LogInformation(

            $”- {nameof(LoggingResponseHeaderFilterService)}.{nameof(OnResultExecuted)}”);

    }

}

In the following code, LoggingResponseHeaderFilterService is added to the DI container:

C#Copy

builder.Services.AddScoped<LoggingResponseHeaderFilterService>();

In the following code, the ServiceFilter attribute retrieves an instance of the LoggingResponseHeaderFilterService filter from DI:

C#Copy

[ServiceFilter(typeof(LoggingResponseHeaderFilterService))]

public IActionResult WithServiceFilter() =>

    Content($”- {nameof(FilterDependenciesController)}.{nameof(WithServiceFilter)}”);

When using ServiceFilterAttribute, setting ServiceFilterAttribute.IsReusable:

  • Provides a hint that the filter instance may be reused outside of the request scope it was created within. The ASP.NET Core runtime doesn’t guarantee:
    • That a single instance of the filter will be created.
    • The filter will not be re-requested from the DI container at some later point.
  • Shouldn’t be used with a filter that depends on services with a lifetime other than singleton.

ServiceFilterAttribute implements IFilterFactory. IFilterFactory exposes the CreateInstance method for creating an IFilterMetadata instance. CreateInstance loads the specified type from DI.

TypeFilterAttribute

TypeFilterAttribute is similar to ServiceFilterAttribute, but its type isn’t resolved directly from the DI container. It instantiates the type by using Microsoft.Extensions.DependencyInjection.ObjectFactory.

Because TypeFilterAttribute types aren’t resolved directly from the DI container:

  • Types that are referenced using the TypeFilterAttribute don’t need to be registered with the DI container. They do have their dependencies fulfilled by the DI container.
  • TypeFilterAttribute can optionally accept constructor arguments for the type.

When using TypeFilterAttribute, setting TypeFilterAttribute.IsReusable:

  • Provides hint that the filter instance may be reused outside of the request scope it was created within. The ASP.NET Core runtime provides no guarantees that a single instance of the filter will be created.
  • Should not be used with a filter that depends on services with a lifetime other than singleton.

The following example shows how to pass arguments to a type using TypeFilterAttribute:

C#Copy

[TypeFilter(typeof(LoggingResponseHeaderFilter),

    Arguments = new object[] { “Filter-Header”, “Filter Value” })]

public IActionResult WithTypeFilter() =>

    Content($”- {nameof(FilterDependenciesController)}.{nameof(WithTypeFilter)}”);

Authorization filters

Authorization filters:

  • Are the first filters run in the filter pipeline.
  • Control access to action methods.
  • Have a before method, but no after method.

Custom authorization filters require a custom authorization framework. Prefer configuring the authorization policies or writing a custom authorization policy over writing a custom filter. The built-in authorization filter:

  • Calls the authorization system.
  • Does not authorize requests.

Do not throw exceptions within authorization filters:

  • The exception will not be handled.
  • Exception filters will not handle the exception.

Consider issuing a challenge when an exception occurs in an authorization filter.

Learn more about Authorization.

Resource filters

Resource filters:

Resource filters are useful to short-circuit most of the pipeline. For example, a caching filter can avoid the rest of the pipeline on a cache hit.

Resource filter examples:

Action filters

Action filters do not apply to Razor Pages. Razor Pages supports IPageFilter and IAsyncPageFilter. For more information, see Filter methods for Razor Pages.

Action filters:

The following code shows a sample action filter:

C#Copy

public class SampleActionFilter : IActionFilter

{

    public void OnActionExecuting(ActionExecutingContext context)

    {

        // Do something before the action executes.

    }

    public void OnActionExecuted(ActionExecutedContext context)

    {

        // Do something after the action executes.

    }

}

The ActionExecutingContext provides the following properties:

  • ActionArguments – enables reading the inputs to an action method.
  • Controller – enables manipulating the controller instance.
  • Result – setting Result short-circuits execution of the action method and subsequent action filters.

Throwing an exception in an action method:

  • Prevents running of subsequent filters.
  • Unlike setting Result, is treated as a failure instead of a successful result.

The ActionExecutedContext provides Controller and Result plus the following properties:

  • Canceled – True if the action execution was short-circuited by another filter.
  • Exception – Non-null if the action or a previously run action filter threw an exception. Setting this property to null:
    • Effectively handles the exception.
    • Result is executed as if it was returned from the action method.

For an IAsyncActionFilter, a call to the ActionExecutionDelegate:

  • Executes any subsequent action filters and the action method.
  • Returns ActionExecutedContext.

To short-circuit, assign Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext.Result to a result instance and don’t call next (the ActionExecutionDelegate).

The framework provides an abstract ActionFilterAttribute that can be subclassed.

The OnActionExecuting action filter can be used to:

  • Validate model state.
  • Return an error if the state is invalid.

C#Copy

public class ValidateModelAttribute : ActionFilterAttribute

{

    public override void OnActionExecuting(ActionExecutingContext context)

    {

        if (!context.ModelState.IsValid)

        {

            context.Result = new BadRequestObjectResult(context.ModelState);

        }

    }

}

 Note

Controllers annotated with the [ApiController] attribute automatically validate model state and return a 400 response. For more information, see Automatic HTTP 400 responses.

The OnActionExecuted method runs after the action method:

  • And can see and manipulate the results of the action through the Result property.
  • Canceled is set to true if the action execution was short-circuited by another filter.
  • Exception is set to a non-null value if the action or a subsequent action filter threw an exception. Setting Exception to null:
    • Effectively handles an exception.
    • ActionExecutedContext.Result is executed as if it were returned normally from the action method.

Exception filters

Exception filters:

The following sample exception filter displays details about exceptions that occur when the app is in development:

C#Copy

public class SampleExceptionFilter : IExceptionFilter

{

    private readonly IHostEnvironment _hostEnvironment;

    public SampleExceptionFilter(IHostEnvironment hostEnvironment) =>

        _hostEnvironment = hostEnvironment;

    public void OnException(ExceptionContext context)

    {

        if (!_hostEnvironment.IsDevelopment())

        {

            // Don’t display exception details unless running in Development.

            return;

        }

        context.Result = new ContentResult

        {

            Content = context.Exception.ToString()

        };

    }

}

The following code tests the exception filter:

C#Copy

[TypeFilter(typeof(SampleExceptionFilter))]

public class ExceptionController : Controller

{

    public IActionResult Index() =>

        Content($”- {nameof(ExceptionController)}.{nameof(Index)}”);

}

Exception filters:

  • Don’t have before and after events.
  • Implement OnException or OnExceptionAsync.
  • Handle unhandled exceptions that occur in Razor Page or controller creation, model binding, action filters, or action methods.
  • Do not catch exceptions that occur in resource filters, result filters, or MVC result execution.

To handle an exception, set the ExceptionHandled property to true or assign the Result property. This stops propagation of the exception. An exception filter can’t turn an exception into a “success”. Only an action filter can do that.

Exception filters:

  • Are good for trapping exceptions that occur within actions.
  • Are not as flexible as error handling middleware.

Prefer middleware for exception handling. Use exception filters only where error handling differs based on which action method is called. For example, an app might have action methods for both API endpoints and for views/HTML. The API endpoints could return error information as JSON, while the view-based actions could return an error page as HTML.

Result filters

Result filters:

IResultFilter and IAsyncResultFilter

The following code shows a sample result filter:

C#Copy

public class SampleResultFilter : IResultFilter

{

    public void OnResultExecuting(ResultExecutingContext context)

    {

        // Do something before the result executes.

    }

    public void OnResultExecuted(ResultExecutedContext context)

    {

        // Do something after the result executes.

    }

}

The kind of result being executed depends on the action. An action returning a view includes all razor processing as part of the ViewResult being executed. An API method might perform some serialization as part of the execution of the result. Learn more about action results.

Result filters are only executed when an action or action filter produces an action result. Result filters are not executed when:

  • An authorization filter or resource filter short-circuits the pipeline.
  • An exception filter handles an exception by producing an action result.

The Microsoft.AspNetCore.Mvc.Filters.IResultFilter.OnResultExecuting method can short-circuit execution of the action result and subsequent result filters by setting Microsoft.AspNetCore.Mvc.Filters.ResultExecutingContext.Cancel to true. Write to the response object when short-circuiting to avoid generating an empty response. Throwing an exception in IResultFilter.OnResultExecuting:

  • Prevents execution of the action result and subsequent filters.
  • Is treated as a failure instead of a successful result.

When the Microsoft.AspNetCore.Mvc.Filters.IResultFilter.OnResultExecuted method runs, the response has probably already been sent to the client. If the response has already been sent to the client, it cannot be changed.

ResultExecutedContext.Canceled is set to true if the action result execution was short-circuited by another filter.

ResultExecutedContext.Exception is set to a non-null value if the action result or a subsequent result filter threw an exception. Setting Exception to null effectively handles an exception and prevents the exception from being thrown again later in the pipeline. There is no reliable way to write data to a response when handling an exception in a result filter. If the headers have been flushed to the client when an action result throws an exception, there’s no reliable mechanism to send a failure code.

For an IAsyncResultFilter, a call to await next on the ResultExecutionDelegate executes any subsequent result filters and the action result. To short-circuit, set ResultExecutingContext.Cancel to true and don’t call the ResultExecutionDelegate:

C#Copy

public class SampleAsyncResultFilter : IAsyncResultFilter

{

    public async Task OnResultExecutionAsync(

        ResultExecutingContext context, ResultExecutionDelegate next)

    {

        if (context.Result is not EmptyResult)

        {

            await next();

        }

        else

        {

            context.Cancel = true;

        }

    }

}

The framework provides an abstract ResultFilterAttribute that can be subclassed. The ResponseHeaderAttribute class shown previously is an example of a result filter attribute.

IAlwaysRunResultFilter and IAsyncAlwaysRunResultFilter

The IAlwaysRunResultFilter and IAsyncAlwaysRunResultFilter interfaces declare an IResultFilter implementation that runs for all action results. This includes action results produced by:

  • Authorization filters and resource filters that short-circuit.
  • Exception filters.

For example, the following filter always runs and sets an action result (ObjectResult) with a 422 Unprocessable Entity status code when content negotiation fails:

C#Copy

public class UnprocessableResultFilter : IAlwaysRunResultFilter

{

    public void OnResultExecuting(ResultExecutingContext context)

    {

        if (context.Result is StatusCodeResult statusCodeResult

            && statusCodeResult.StatusCode == StatusCodes.Status415UnsupportedMediaType)

        {

            context.Result = new ObjectResult(“Unprocessable”)

            {

                StatusCode = StatusCodes.Status422UnprocessableEntity

            };

        }

    }

    public void OnResultExecuted(ResultExecutedContext context) { }

}

IFilterFactory

IFilterFactory implements IFilterMetadata. Therefore, an IFilterFactory instance can be used as an IFilterMetadata instance anywhere in the filter pipeline. When the runtime prepares to invoke the filter, it attempts to cast it to an IFilterFactory. If that cast succeeds, the CreateInstance method is called to create the IFilterMetadata instance that is invoked. This provides a flexible design, since the precise filter pipeline doesn’t need to be set explicitly when the app starts.

IFilterFactory.IsReusable:

  • Is a hint by the factory that the filter instance created by the factory may be reused outside of the request scope it was created within.
  • Should not be used with a filter that depends on services with a lifetime other than singleton.

The ASP.NET Core runtime doesn’t guarantee:

  • That a single instance of the filter will be created.
  • The filter will not be re-requested from the DI container at some later point.

 Warning

Only configure IFilterFactory.IsReusable to return true if the source of the filters is unambiguous, the filters are stateless, and the filters are safe to use across multiple HTTP requests. For instance, don’t return filters from DI that are registered as scoped or transient if IFilterFactory.IsReusable returns true.

IFilterFactory can be implemented using custom attribute implementations as another approach to creating filters:

C#Copy

public class ResponseHeaderFilterFactory : Attribute, IFilterFactory

{

    public bool IsReusable => false;

    public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) =>

        new InternalResponseHeaderFilter();

    private class InternalResponseHeaderFilter : IActionFilter

    {

        public void OnActionExecuting(ActionExecutingContext context) =>

            context.HttpContext.Response.Headers.Add(

                nameof(OnActionExecuting), nameof(InternalResponseHeaderFilter));

        public void OnActionExecuted(ActionExecutedContext context) { }

    }

The filter is applied in the following code:

C#Copy

[ResponseHeaderFilterFactory]

public IActionResult Index() =>

    Content($”- {nameof(FilterFactoryController)}.{nameof(Index)}”);

IFilterFactory implemented on an attribute

Filters that implement IFilterFactory are useful for filters that:

  • Don’t require passing parameters.
  • Have constructor dependencies that need to be filled by DI.

TypeFilterAttribute implements IFilterFactory. IFilterFactory exposes the CreateInstance method for creating an IFilterMetadata instance. CreateInstance loads the specified type from the services container (DI).

C#Copy

public class SampleActionTypeFilterAttribute : TypeFilterAttribute

{

    public SampleActionTypeFilterAttribute()

         : base(typeof(InternalSampleActionFilter)) { }

    private class InternalSampleActionFilter : IActionFilter

    {

        private readonly ILogger<InternalSampleActionFilter> _logger;

        public InternalSampleActionFilter(ILogger<InternalSampleActionFilter> logger) =>

            _logger = logger;

        public void OnActionExecuting(ActionExecutingContext context)

        {

            _logger.LogInformation(

                $”- {nameof(InternalSampleActionFilter)}.{nameof(OnActionExecuting)}”);

        }

        public void OnActionExecuted(ActionExecutedContext context)

        {

            _logger.LogInformation(

                $”- {nameof(InternalSampleActionFilter)}.{nameof(OnActionExecuted)}”);

        }

    }

}

The following code shows three approaches to applying the filter:

C#Copy

[SampleActionTypeFilter]

public IActionResult WithDirectAttribute() =>

    Content($”- {nameof(FilterFactoryController)}.{nameof(WithDirectAttribute)}”);

[TypeFilter(typeof(SampleActionTypeFilterAttribute))]

public IActionResult WithTypeFilterAttribute() =>

    Content($”- {nameof(FilterFactoryController)}.{nameof(WithTypeFilterAttribute)}”);

[ServiceFilter(typeof(SampleActionTypeFilterAttribute))]

public IActionResult WithServiceFilterAttribute() =>

    Content($”- {nameof(FilterFactoryController)}.{nameof(WithServiceFilterAttribute)}”);

In the preceding code, the first approach to applying the filter is preferred.

Use middleware in the filter pipeline

Resource filters work like middleware in that they surround the execution of everything that comes later in the pipeline. But filters differ from middleware in that they’re part of the runtime, which means that they have access to context and constructs.

To use middleware as a filter, create a type with a Configure method that specifies the middleware to inject into the filter pipeline. The following example uses middleware to set a response header:

C#Copy

public class FilterMiddlewarePipeline

{

    public void Configure(IApplicationBuilder app)

    {

        app.Use(async (context, next) =>

        {

            context.Response.Headers.Add(“Pipeline”, “Middleware”);

            await next();

        });

    }

}

Use the MiddlewareFilterAttribute to run the middleware:

C#Copy

[MiddlewareFilter(typeof(FilterMiddlewarePipeline))]

public class FilterMiddlewareController : Controller

{

    public IActionResult Index() =>

        Content($”- {nameof(FilterMiddlewareController)}.{nameof(Index)}”);

}

Middleware filters run at the same stage of the filter pipeline as Resource filters, before model binding and after the rest of the pipeline.

Leave a Comment

Your email address will not be published. Required fields are marked *

https://www.cooljerseyedge.com, https://www.collegeshopfan.com, https://www.kcchiefsgearusa.com, https://www.dlionsgearusa.com, https://www.bravensgearusa.com, https://www.cbengalsgearusa.com, https://www.gbpackersgearusa.com, https://www.htexansgearusa.com, https://www.laramsgearusa.com, Josh Allen Wyoming Jersey, https://www.dcowboysgearusa.com, https://www.mdolphinsgearusa.com, https://www.aliexfanshop.com, https://www.bestplayershop.com, https://www.collegeedgeshop.com, https://www.giantsonlinefans.com