Search code examples
c#asp.net-coreasp.net-core-middleware

RequestDelegate as discard parameter in custom middleware class


I saw the following code:

class ReaderMiddleware
{
    IReader reader;
 
    public ReaderMiddleware(RequestDelegate _, IReader reader) => this.reader = reader;
     
    public async Task InvokeAsync(HttpContext context)
    {
        await context.Response.WriteAsync($"Current Value: {reader.ReadValue()}");
    }
}

_ assumes not used in code argument. According to MSDN:

... isn't assigned a value, and may not even be assigned a storage location.

Why the author of the post uses it in class if RequestDelegate is a mandatory parameter? Does it mean that no other middleware is used after it?


Solution

  • Usually, a middleware component is responsible for calling the next item in the pipeline. See this example in the docs:

    enter image description here

    However, in the code you show, this is an example of terminal middleware because it does not process any more in the chain. This is why the author has discarded the RequestDelegate parameter. Another option would be to completely elide that parameter entirely:

    public ReaderMiddleware(IReader reader) => this.reader = reader;
    

    If you wanted to extend the middleware to call the next in the chain, you would do something like this:

    class ReaderMiddleware
    {
        RequestDelegate next;
        IReader reader;
    
        public ReaderMiddleware(RequestDelegate next, IReader reader)
        {
            this.next = next
            this.reader = reader;
        }
         
        public async Task InvokeAsync(HttpContext context)
        {
            await context.Response.WriteAsync($"Current Value: {reader.ReadValue()}");
    
            // Call the next middleware in the pipeline
            await next();
        }
    }