ASP.NET CORE – custom middleware

ASP.NET Core gives developers flexibility and control over HTTP requests. We can customize requests pipeline by creating middlewares. They allow developers to plug in request handlers like static file providers, authentication or error pages. ASP.NET Core has a lot of them built in. (MVC for example). You can also create your own middleware in only few steps.

First create a new project.

and select a template. Web API is ok.

Then create a new middleware class.

Here is a basic pattern for middleware.

 public class SimpleMiddleware
    {
        private readonly RequestDelegate next;

        public SimpleMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            await next.Invoke(context);
        }
    }

As you can see each middleware must implement an async task called Invoke.
Middleware works by processing HttpContext object. It gives you a full control over request and further response.
RequestDelegate object helps invoking next component in pipeline.

Let’s create a simple middleware for greetings. The middleware should say ‘Hi’ to every person which name will be in query string.
Additional requirements:
– endpoint should ends with “/greeting”
– only supported method should be GET
– only valid parameter in query string should be “names”

 public class GreetingMiddleware
    {
        private readonly RequestDelegate next;

        public GreetingMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            context.Response.StatusCode = 400;

            if (!context.Request.Path.Equals("/greeting", StringComparison.Ordinal))
            {
                await context.Response.WriteAsync("Invalid request path");
                return;
            }

            if (!context.Request.Method.Equals("GET"))
            {
                await context.Response.WriteAsync($"{context.Request.Method} Method not supported");
                return;
            }

            if (!context.Request.Query.Any() || string.IsNullOrEmpty(context.Request.Query["names"]))
            {
                await context.Response.WriteAsync("Invalid or empty query string");
                return;
            }
            
            context.Response.StatusCode = 200;
            var names = context.Request.Query["names"].ToString().Split(',').ToList();
            var sb = new StringBuilder();
            names.ForEach(n => sb.Append($"Hi {n}{Environment.NewLine}"));
            await context.Response.WriteAsync(sb.ToString());
            return;
        }
    }

All done. Now it is time to add your middleware to application pipeline. Just add the following line into Configure method in Startup.cs class.

app.UseMiddleware<GreetingMiddleware>();

Test it using Postman. You can download it here.

Everything works as we planned. Enjoy!

Leave a Reply

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