When building web applications in .NET, middleware plays a big role in handling incoming requests. In this blog post, we'll break down three important request-handling methods: Use(), Map(), and Run() – what they do, how they work, and when to use them.
What is Middleware?
Middleware in .NET is a piece of code that runs between the server receiving a request and the server sending a response. It can perform tasks like:
- Logging
- Authentication
- Exception handling
- Modifying requests/responses
Now let’s explore the three key methods used in setting up middleware: Use(), Map(), and Run().
Use() Method
The Use() method is used to add middleware components to the request pipeline. It can pass control to the next middleware using next().
Key Points:
- Can call the next middleware using next().
- Used for logging, authentication, exception handling, etc.
- If next() is not called, it short-circuits the pipeline.
Map() Method
The Map() method is used to create branches in the request pipeline. It runs specific middleware only if the request path matches a pattern.
Key Points:
- Routes requests to different branches.
- Used for API versioning, feature-based middleware, etc.
- Middleware inside Map() runs only if the path matches.
Run() Method
The Run() method is used to create terminal middleware — this means it handles the request and does not call any other middleware after it.
Key Points:
- Ends the middleware pipeline.
- Does not call the next middleware.
- Used for simple, final request handling.
Conclusion
By using Use(), Map(), and Run(), you can structure your request handling in .NET applications effectively:
- Use Use() to chain middleware.
- Use Map() to create route-specific middleware branches.
- Use Run() to finalize the request pipeline.
Top comments (0)