Creating a simple MiddlewareFilter using .NET Core 2.0 and dependency injection

MiddlewareFilter is the perfect tool for creating conditional logic on MVC controllers or actions using .NET Core. It receives the Middleware benefits of natural dependency injection, and also can dip into the MVC pipeline. You can use it conditionally, see current MVC routes, and also short-circuit before the MVC action happens. Here is how to set one up.

The Code

First, set up any custom logic you want to run in your MiddlewareFilter:

public class SomeMiddlewareStuff
{
    private readonly IClaimsManager _claimsManager;
	
	public SomeMiddlewareStuff(RequestDelegate next, IClaimsManager claimsManager)
		{
			_next = next;
			_claimsManager = claimsManager;
		}

		public async Task Invoke(HttpContext context)
		{
			// Any logic you want, short-circuit if you do not want the request to continue
			{
				throw new Exception();
			}

			await _next(context);
		}
	}
}

Then create the code to register your attribute in the pipeline. Since middleware is designed to run before MVC actions, this code interjects the logic of the MiddlewareFilter directly before the action runs.

public class SomeMiddlewareStuffAttribute
{
	public void Configure(IApplicationBuilder app)
	{
		app.UseMiddleware<SomeMiddlewareStuff>();
	}
}

Finally, slap the attribute on any MVC controllers or actions you want the logic to run on.

[MiddlewareFilter(typeof(SomeMiddlewareStuffAttribute))]
public ActionResult SomeControllerAction()
{
	// Whatever

	return Ok();
}

Enjoy!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.