Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading