How to use Resource filter in ASP.NET Core MVC?
As with name indicate this Resource filter can be used for handling Resources and helps to ShortCircuit if required in the execution pipeline.
Resource filters are the first to handle a request after authorization. They can run code before the rest of the filter pipeline, and after the rest of the pipeline has completed.
Resource filter is useful to implement caching or otherwise short-circuit the filter pipeline for performance reasons. It runs before model binding, so it can influence model binding.
Properties of Resource filters
Implement either the IResourceFilter or IAsyncResourceFilter interface,
- Their execution wraps most of the filter pipeline.
- Only Authorization filters run before Resource filters.
Caching filter can avoid the rest of the pipeline if the response is in the cache i.e ShortCircuiting.
Can be used for,
- Prevents model binding from accessing the form data.
- Useful for large file uploads and prevent a form from being read into memory.
A common use of Resource Filters in,
- Logging
- Caching
- Throttling
- Modifying model binding
An IResourceFilter interface has two methods one is OnResourceExecuting with parameter ResourceExecutingContext and OnResourceExecuted with parameter ResourceExecutedContext similar to Action Filter.
A simple ShortCircuiting resource filter looks like,
public class SCResourceFilterAttribute
: Attribute, IResourceFilter
{
public void OnResourceExecuting(
ResourceExecutingContext context)
{
//As context.Result is of type IActionResult
//So you can think what we can pass with it.
context.Result = new ContentResult()
{
//We can set ContentType, StatusCode & Content
//Set as per your need
Content = "Resource unavailable - header should not be set"
};
}
public void OnResourceExecuted(
ResourceExecutedContext context)
{
}
}
Now to use this Resource Filter we just have to use this Attribute where we need it, like
[SCResourceFilter]
public IActionResult AppResource()
{
return Content("A Successful message - header should be set.");
}
So use it when it fits for the projects.