Request Filtering in ASP.NET Core using Middleware and request pipeline

Filter requests in ASP.NET Core application through request pipeline configuration

ASP.NET Core comes with advanced request processing thrugh pipepline configuretion of the .NET Core middleware elements. You can easily specify the steps that will be exscuted on the request object all the way until the response is returned back. Before .NET Core this functionality was achieved with System.Web.IHttpModule interface class implementation.

You could write your own implementation of System.Web.IHttpModule and configure it inside the web.config file. Since System.Web is now obsolete and decopled into smaller units, you cannot use this way of request proecessiong in ASP.NET Core. Instead there is a Request pipeline which comes with ASP.NET Core where you can declare you actions on the request either with inline functions or inside separate classes.

Core Pipeline

This is done in Startup.cs class inside Configure method. You can declare three basic types of pipeline action and those are:

  • Use - execute delegate and go to next pipeline step
  • Map - conditionally execute delegate and return result
  • Run - execute delegate and return result

We are going to stick to Map action, specifically to MapWhen extension on the IApplicationBuilder interface. This method takes two arguments:

  1. Function which takes IHttpContext as an input parameter and returns bool value System.Func<HttpContext, bool>
  2. Delegate Action which has IApplicationBuilder as an input System.Action<IApplicationBuilder>

MapWhen behaves same as Map which means it does not go to next middleware in the pipeline after execution of the delegate, but in addition has a condition which decides whether action will be executed or not.

For the sample project used default ASP.NET Web API project and configured filtering of the request based on the Content-Type header value. The following is the modified Configure method in the Startup.cs class

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.MapWhen(context => !String.IsNullOrWhiteSpace(context.Request.ContentType) && context.Request.ContentType.Equals("text/xml", StringComparison.InvariantCultureIgnoreCase),
                (IApplicationBuilder appBuilder) =>
                {
                   appBuilder.Run(async context =>
                   {
                       await Task.FromResult(context.Response.StatusCode = StatusCodes.Status406NotAcceptable);
                   });
                });

            app.UseMvc();
        }
    

This simple filtering will generate response in case value of Content-Type header key of the request is not equal to text/xml, otherwise it will return an empty content with status code 406 Not Acceptable. Let's spin it up and test using POSTMAN tool.

First let's invoke the URL with Content-Type set to application/json

Core Filter Appjson

We got the normal 200 OK response with JSON response message of the default API project Value controller action. Now let's test our MapWhen action which will be triggered in case Content-Type is text/xml.

Core Filter Txtxml

You can see that response is as we set it in our inline delegate function to be 406 Not Acceptable.

Note

Pipeline middleware elements are executed in the same order as they are declared in code, so make sure you define your filtering MapWhen statement at the top of Configure method steps in order to intercept Request before other action in the pipeline stack.

This is a simple example of request filtering based on Content-Type header key value. same way you can filter request based on IP, UserAgent or any other property available in the HttpContext

References

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform includion ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article