We will explore all aspect of middleware building in this section.
-
ASP.NET Core is built on top of pipelines of functions called middleware. This sample shows the basic outline on how they work.
We are using
IApplicationBuilder Use
, an extension method for adding middleware andIApplicationBuilder Run
. -
This example shows how to pass information from one middleware to another using
HttpContext.Items
. -
As a general rule, only one of your Middleware should write to Response in an execution path. This sample shows how to work around this by buffering the Response.
e.g.
If path
/
involves the execution of Middleware 1, Middleware 2 and Middleware 3, only one of these should write to Response. -
This is the simplest middleware class you can create.
-
Use
app.Map
(MapMiddleware
) to configure your middleware pipeline to respond only on specific url path. -
Nested
app.Map
(showRequest.Path
andRequest.PathBase
). -
Use
app.MapWhen
(MapWhenMiddleware
) and Nestedapp.Map
(showRequest.Path
andRequest.PathBase
). -
Use
MapMiddleware
andMapWhenMiddleware
directly without using extensions (showRequest.Path
andRequest.PathBase
). -
Demonstrate the various ways you can inject dependency to your middleware class manually.
-
Demonstrate how to ASP.NET Core built in DI (Dependency Injection) mechanism to provide dependency for your middleware.
-
Demonstrate that a middleware is a singleton.
-
This sample is similar to
Middleware 10
except that this one implementIMiddleware
to create Factory-based middleware activation. This means that you can create a middleware that is not a singleton (either Transient or Scoped). -
Contrast the usage of
MapWhen
(which branch execution) andUseWhen
(which doesn't branch execution) in configuring your Middleware. -
Demonstrate how to implement basic error handling mechanism and how to return error object (same for all api exceptions).