Search This Blog

Filters in ASP NET Core - what are they and how to use them

Filters in ASP NET Core - what are they and how to use them

ASP NET Core comes with a concept of filters. Filters intercept the stages of the MVC pipeline and allows us to run code before/after their executions. They are meant to be used for cross-cutting concerns; logics which is required accross the whole application, generally not business oriented. One example is authorization where in a Web API, we would use to prevent unauthorized request to execute the code in our controllers. In order to do that we would have a filter at the entrance of the pipeline. In fact, ASP NET Core has predefine stages, the diagram can be found on the documentation https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters. Another example of a cross-cutting concern would be for logging and timing functions. While the concept of filters is easy to understand, the way to implement those aren’t always straight forward, especially when the filter instantiation itself requires simple objects. In order to illustrate our example we will only filter the Action stage. The same implementations can be applied to any stages of MVC pipeline.

Today I will explain the different ways to create filters. This post will be composed by 5 parts:

1. Simple action filter with ActionFilterAttribute base

ASP NET Core comes with default empty implementation of the filter iterfaces. One of those is ActionFilterAttribute which implements IActionFilter and inherit from Attribute.
We can use it to easily add filter logic before and after the action is invoked:

Now if we need to use the service within the filter, we will need a way to resolve the filter using the service provider so that before that it will automatically resolve our service.
That’s where service filter comes into picture. We can use the service filter directly on the action and pass the type of our filter implementation.

Since our filter is resolved from the service provider, we need to register it.

When the action is invoked the filter will have the proper service injected. The advantage of the service filter is that we can manage the life cycle scoped, transient or singleton depending on how we registered it in Startup.cs.

Now if we needed extra arguments to our filter, we can no longer resolve it via service filter.

4. Use TypeFilterAttribute

If the arguments needed fit into the attributes argument constrain, we can use TypeFilter.
For example, if our service needs an extra string argument which can’t be resolved via DI:

The difference with the service filter is that the type filter instiantes the filter using the type provided and the arguments as opposed to the service filter which gets the instance from the service provider.

Since arguments in the filter are restricted by the attribute arguments, we can’t have typical class passed. ServiceFilter and TypeFilter are actually implementation of IFilterFactory. If we want to have full control on the instantiation, we can implement the factory ourselves.

public class Hello5FilterAttribute: Attribute, IFilterFactory
{
private string _extraText;
// Indicates if the filter created can be reused accross requests.
public bool IsReusable => false;
public Hello5FilterAttribute(string extraText)
{
_extraText = extraText;
}
public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
{
// GetRequiredService<>() is available in Microsoft.Extensions.DependencyInjection
// GetRequiredService VS GetService is that Required will throw exception when service can't be found, while the other will return null.
return new Hello5FilterImpl(
serviceProvider.GetRequiredService<IHelloService>(),
_extraText,
new HelloOptions { Text = "text from options" });
}
}

The factory also have a property IsReusable which indicates if the filter created by the factory can be reused accross requests. If set to false, it will be instantiated per request.
We can then use the factory like so:

Conclusion

Today we saw how we could use the different filter implementations available in ASP NET Core to provide cross cutting concern. Depending on your needs, you can choose between implementing a simple filter or using service filter or type filter. Lastly if your requirements are more advanced, implementing yourself the filter factory will allow you to have full control. Hope you enjoyed this post as much as I enjoyed writing it! If you have any question leave it here or hit me on Twitter @Kimserey_Lam. See you next time!

Comments

Post a Comment

Popular posts from this blog

Absolute layout and relative layout Xamarin formsIn Xamarin Forms, layouts are used to position elements in the page.
There are multiple layouts available like stack layout, grid layout, table layout, absolute layout and relative layout.
Stack layout is straight to grasp the concept, we stack elements one by one horizontally or vertically.
Grid layout is also straight forward, we define rows and columns and we place the elements by indicating the row index and column index.
On the other hand, absolute layout and relative layout isn’t that straight forward because in Xamarin it is NOT the same as positions in CSS.So today, we will see how and when we can use absolute layout and/or relative layout in our advantage.
This post is composed by two parts: 1. Absolute layout
2. Relative layout
1. Absolute layoutThe first thing to understand is that absolute layout has nothing to do with CSS absolute position.
In Xamarin Forms. absolute layout allows us to position elements in the page by pre…

Build an accordion view in Xamarin.FormsFew weeks ago I posted about absolute and relative layouts.
Layouts are called Layouts because they contain children which are placed in a particular way.
Xamarin.Forms has a lot of layouts and views to structure pages like grid, table view or list view.Today I would like to show you how we can use some of these basic views to build an Accordion view.Here’s a preview of the Accordion view:Full source code available on GitHub - https://github.com/Kimserey/AccordionView/blob/master/Accordion/AccordionView.csThis post will be composed of four steps:Create a BindablePropertyDefine the accordion expandable sectionDefine the accordion viewUsage sample1. Create a BindablePropertyAs we saw in one of my previous post,
Xamarin.Forms works around data bindings.
View properties are bound to viewmodel properties.Default views like Label, Button, ListView or TableView come with the necessary bindable properties like BackgroundColor, TextColor, ItemsSource, It…

Use Font Awesome from your Xamarin.Forms projectIcons are important in mobile applications where space is limited.
We use icon everywhere to convey action intent like + would be to add an item or a bin would be to delete one.
There are two ways to add icons to our mobile app:with imageswith fontsToday we will see the second option - how we can add Font awesome to our Xamarin.Android project and how we can use it from Xamarin.Forms.
This post will be composed by three parts: 1. Why Font Awesome
2. Add Font Awesome to the Droid project
3. Use with Xamarin.Forms
1. Why Font AwesomeIf you are familiar with Web development, you must have encountered Font awesome http://fontawesome.io/.
It is an icon font containing lots of icon for every type of usage.
The advantaged of using a font is that we can leverage the text options, like text color or text size, to easily update the style of the icon to match our app.Let’s see how we can bring Font Awesome to the Droid project.2. Add Font awesome…