Built-in Middleware in ASP.NET Core
- UseWhen
- MapWhen
- UseRouting
- UseEndpoints
UseWhen and MapWhen middleware
In ASP.NET Core, both UseWhen and MapWhen allow conditional branching in the middleware pipeline, but they serve slightly different purposes and behave differently in how they handle the pipeline. Here’s a breakdown of each:
1. UseWhen
- Purpose: UseWhen conditionally runs a piece of middleware based on a predicate. If the condition is met, it executes a branch of middleware; if not, it continues with the main pipeline.
- Pipeline Continuation: After the UseWhen middleware branch is executed (if the condition is met), the request returns to the main pipeline and continues processing the remaining middleware.
- Common Usage: Used when you want conditional execution but still need to continue processing in the main pipeline.
Example:
app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), branch =>
{
branch.Use(async (ctx, next) =>
{
// Code only runs for requests starting with /api
await next();
});
});
// Continues with the main pipeline even if /api condition is met.
app.Use(async (ctx, next) =>
{
// This code runs for all requests, including /api.
await next();
});
2. MapWhen
- Purpose: MapWhen also conditionally branches the middleware pipeline, but instead of returning to the main pipeline after executing the branch, it starts a separate branch. Only one branch executes depending on the condition, meaning it does not return to the main pipeline after branching.
- Pipeline Separation: If the condition is met, only the middleware in the MapWhen branch executes; the main pipeline does not continue. If the condition is not met, the main pipeline continues as usual, and the mapped branch is skipped.
- Common Usage: Useful when you want to create entirely separate request processing paths without merging back into the main pipeline.
Example:
app.MapWhen(context => context.Request.Path.StartsWithSegments("/api"), branch =>
{
branch.Use(async (ctx, next) =>
{
// Code only runs for requests starting with /api
await next();
});
// Additional middleware specific to /api path can be added here.
});
// Continues with the main pipeline only if the /api condition is NOT met.
app.Use(async (ctx, next) =>
{
// This code runs only if the /api condition was NOT met.
await next();
});
Key Differences Summary
- Use UseWhen if you need conditional middleware but want to return to the main pipeline afterward.
- Use MapWhen if you need to branch out with separate request processing paths without returning to the main pipeline.
UseRouting and UseEndpoints middleware
In ASP.NET Core, UseRouting and UseEndpoints are key middleware components for request routing, but they serve distinct roles in the request pipeline:
1. UseRouting
Purpose: UseRouting middleware is responsible for matching incoming requests to endpoint route definitions (such as controller actions, Razor pages, or minimal APIs) based on the URL and HTTP method.
Functionality: It finds the endpoint that corresponds to the request but does not execute it. UseRouting essentially prepares the request context by determining the intended endpoint, which can then be used by subsequent middleware.
Placement in Pipeline: It should be placed before any middleware that relies on route information, like UseAuthorization, UseCors, or UseEndpoints.
Example:
app.UseRouting();
2. UseEndpoints
Purpose: UseEndpoints middleware is responsible for executing the endpoint selected by UseRouting.
Functionality: Once UseRouting identifies the endpoint, UseEndpoints invokes it. This is where the matched endpoint (e.g., an MVC action, Razor page, or API route) is actually processed.
Placement in Pipeline: It should be placed after UseRouting and any other middleware that requires routing data, such as authorization or CORS policies.
Example:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers(); // Executes matched controller endpoints
endpoints.MapRazorPages(); // Executes matched Razor page endpoints
});
Key Differences Summary
Feature | UseRouting | UseEndpoints |
---|---|---|
Purpose | Matches requests to endpoints based on routing | Executes the matched endpoint |
Functionality | Identifies the route but does not execute it | Executes the selected route’s handler |
Pipeline Placement | Typically early, before authorization or CORS | After UseRouting and any routing-dependent middleware |
Common Usage | Needed for route matching to occur in the pipeline | Needed to run matched endpoints like controllers |
Example in Middleware Pipeline
Here’s a typical setup in an ASP.NET Core app:
public void Configure(IApplicationBuilder app)
{
app.UseRouting(); // Matches requests to endpoints
app.UseAuthorization(); // Uses routing data for authorization
app.UseEndpoints(endpoints => // Executes matched endpoints
{
endpoints.MapControllers();
});
}
In summary:
- UseRouting is for setting up routing data based on the request URL and HTTP method.
- UseEndpoints is for actually running the endpoint handler matched by UseRouting.
Some Routing Terms
Explain these related terms: Route Template, Route Handler, Route Constraints and Route Endpoint.
In ASP.NET Core, routing is the process that maps incoming requests to the corresponding endpoints (like controllers or Razor pages) based on URL patterns and HTTP methods. Here's an explanation of the related terms:
1. Route Template
- Definition: A route template is a string pattern that defines the structure of a URL. It specifies placeholders for URL segments that can capture values from the URL and bind them to parameters in the handler (e.g., an action method).
- Example: "api/products/{id:int}" Here, api/products is the fixed part of the route, and {id:int} is a placeholder for a parameter named id, which expects an integer (int is a constraint).
- Usage: Route templates are used to define URL paths in controllers, Razor pages, and minimal APIs.
2. Route Handler
- Definition: A route handler is the component that processes the request once a route is matched. In ASP.NET Core, the route handler could be an action method in a controller, a Razor page, or a delegate in minimal APIs.
- Example: [HttpGet("api/products/{id}")] public IActionResult GetProduct(int id) { // Method that handles the matched route } In this case, GetProduct is the route handler for the route api/products/{id}.
- Usage: Route handlers contain the logic that runs when the route is matched and are often associated with specific HTTP methods (GET, POST, etc.).
3. Route Constraints
- Definition: Route constraints are rules applied to route parameters to restrict which URLs match a route template. They validate whether the parameter value meets specific conditions before considering the route a match.
- Example: {id:int}, {name:alpha}, {date:datetime}
- {id:int} specifies that the id parameter must be an integer.
- {name:alpha} requires that the name parameter consists of alphabetic characters only.
- Usage: Route constraints improve routing precision, ensuring that only valid URLs trigger a route handler. If a URL does not meet a route constraint, it will not match the route, and routing continues to look for other potential matches.
4. Route Endpoint
- Definition: A route endpoint is the final destination for a route match. It represents the combination of a route template, route handler, and associated metadata (such as HTTP methods, authorization policies, etc.).
- Example: In ASP.NET Core, an endpoint might be a specific controller action that has been mapped to a route.
- Usage: Endpoints are the target that routing middleware ultimately resolves and executes after matching a route template. In ASP.NET Core, these are defined in UseEndpoints:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers(); // Creates endpoints for controller actions
});
Summary of Terms
- Route Template: Pattern that defines the structure of the URL and may include parameters ({id}, {name}).
- Route Handler: The method or delegate that processes the request for a matched route (e.g., controller action).
- Route Constraints: Rules applied to route parameters to validate values (int, alpha, datetime).
- Route Endpoint: The final target for a matched route, including template, handler, and metadata (like HTTP methods).
In essence:
- Route templates define URL patterns.
- Route handlers execute logic for the route.
- Route constraints validate route parameters.
- Route endpoints are the overall target that routes resolve and execute in the application.
No comments:
Post a Comment