Use of Middleware in ASP.NET Core 3.1 - Lesson 2

Use of Middleware in ASP.NET Core 3.1 - Lesson 1


This article is a continuation of the previous article.


Middleware is defined with a constructor that takes a RequestDelegate argument.


The Request is populated automatically and gives you a reference to the next piece of middleware in the pipeline.


The Invoke method is where the middleware does its work.


using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace Middleware
{
    public class CustomMiddleware
    {
        private readonly RequestDelegate _next;
        public CustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            //Basic Authentication
            var auth = httpContext.Request.Headers.Keys.Contains("Authorization");
            if(!auth)
            {
                httpContext.Response.StatusCode = 400;
                await httpContext.Response.WriteAsync("Invalid Request");
            }

            await _next.Invoke(httpContext);
        }
    }
}

UseWhen()


The UseWhen() method in ASP.NET Core is an extension method. You can use this method to enable middleware based on specific conditions.


- Right click the Controllers folder. Add API Controller named ValuesController.cs


middleware4.png

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace Middleware.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        // GET: api/
        [HttpGet]
        public IEnumerable Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api//5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }
    }
}

- Open the Startup.cs file and Modify the Configure method as shown below.


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
	//app.UseCustomMiddleware();

	app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), appBuilder =>
	{
		appBuilder.UseMiddleware();
	});

	...
}

- Start the project


middleware5.png

You can access the '/ weatherforecast' path as shown above, but not the '/ api' path. Because you don't have an authorization header.


middleware6.png

POSTMAN


middleware7.png

Using POSTMAN, add an authorization header as follows. You will see the json data in the response body


middleware8.png

Unlike the MapWhen() extension method, the UseWhen() extension method doesn't stop executing the rest of the pipeline as long as there is no short circuit.


MapWhen()


- Add a new class named MyMiddleware


using Microsoft.AspNetCore.Http;
using System.Diagnostics;
using System.Threading.Tasks;

namespace Middleware
{
    public class MyMiddleware
    {
        private readonly RequestDelegate _next;
        public MyMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            Debug.WriteLine("MyMiddleware triggered.");
            await _next.Invoke(httpContext);
        }
    }
}


- Modify the MiddlewareExtension.cs file as follows. Add the UseMyMiddleware extension method.


public static class MiddlewareExtension
{
	public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder app)
	{
		app.UseMiddleware();
		return app;
	}

	public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder app)
	{
		app.UseMiddleware();
		return app;
	}
}

- Modify the Startup.cs file as follows. Add the MapWhen() extension method.


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
	//app.UseCustomMiddleware();
	app.MapWhen(context => context.Request.Path.StartsWithSegments("/api"), appBuilder =>
	{
		appBuilder.UseMiddleware();
	});
	app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), appBuilder =>
	{
		appBuilder.UseMiddleware();
	});
	...
}

- Start the project and go to the '/api/values' path.


middleware9.png

As you can see above, the MapWhen() extension method stops executing the rest of the pipeline. CustomMiddleware did not execute. Also there is no short circuit in MyMiddleware.


Download the source code.