简体   繁体   中英

Run method in custom middleware class on response direction of ASP.Net Core pipeline

The ASP.Net Core Middleware Pipeline is bi-directional , and in the documentation, we see that logic is run in both directions of the pipeline:

在此处输入图像描述

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 (ie the "//more logic" steps in the diagram above.)

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.

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();

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM