A middleware should always invoke the next?

后端 未结 1 1823
太阳男子
太阳男子 2020-12-17 15:27

I\'ve been trying to understand how ASP.NET 5 pipeline middlewares really work. A middleware, as I know, is just a Func,

1条回答
  •  独厮守ぢ
    2020-12-17 16:34

    Middleware exist to make the request pipeline modular, meaning that you can add/remove/replace parts from it as long as you respect the contract. For example, if your application serves some files without any caching, you can add a middleware at the front of the pipeline without altering the rest. They are building blocks.

    A middleware can:

    1. Do nothing and pass the request further (e.g. a middleware that is applicable only to POST requests but the current one is GET)
    2. Do nothing to the request, do something else instead and pass it further (e.g. logging)
    3. Do something to the request and pass the request further (e.g. get an authentication token and convert it to an identity, or remove some sensitive information from the request)
    4. End the pipeline and not pass the request further (e.g. StaticFileMiddleware which just returns the file, or MVC when a route matches)

    Probably answering your other question too: there are two types of middleware:

    1. Middleware that are designed to do something and pass the data along further (etc. auth, cookies, validation, logging etc)
    2. Middleware that complete the pipeline (static file, MVC, etc).

    Of course, some might do both depending on the context. For example auth can end the pipeline if the credentials are incorrect but continue otherwise.

    The author of the middleware must decide if the next middleware (if any) should be invoked. In the case of the middleware in your question which returns a message, it should not invoke the next one.

    0 讨论(0)
提交回复
热议问题