Home > Software engineering >  Run method in custom middleware class on response direction of ASP.Net Core pipeline
Run method in custom middleware class on response direction of ASP.Net Core pipeline

Time:04-13

enter image description here

However, when writing custom middleware, I cannot find an example of running logic on the "response" direction of the flow in the pipeline.

For example, a simple middleware Invoke method

public async Task Invoke(HttpContext context)
{
     // Do some work with the request/ add stuff to the response
     // Pass to next middleware in request direction
     await _next(context);

}

As far as I understand, the Invoke method is only run once, in the "request" direction of the middleware pipeline. Is there another method of the middleware class that can be run in the "response" direction of the pipeline (i.e. the "//more logic" steps in the diagram above.)

CodePudding user response:

The request is just passed down, in order of registration, to each of the middlewares. There is no 'Request' direction and there is no 'Response' direction or specific way to register for one direction or the other.

Your middleware just decides to write the request object or the response object of the HttpContext. But be careful, if the response is already being sent to the client and you start modifying it, errors can get throw.

CodePudding user response:

What @Josh said is very good I just want to add some point which may be what you want.

app.Use(async (context, next) =>
{
    await context.Response.WriteAsync("go into the first middleware\r\n");
    //call next middleware
    await next.Invoke();
    await context.Response.WriteAsync("end first middleware\r\n");
});
app.Use(async (context, next) =>
{
    await context.Response.WriteAsync("go into the second middleware\r\n");
    //call next middleware
    await next.Invoke();
    await context.Response.WriteAsync("end second middleware\r\n");
});
app.Run(async context =>
{
    await context.Response.WriteAsync("go into run middleware\r\n");
    await context.Response.WriteAsync("Hello from run.\r\n");
    await context.Response.WriteAsync("end run\r\n");
});
app.Run();

enter image description here

  • Related