Basic programming, .NET technology.

9. [Updated] - ASP .Net core - Fundamentals - Routing

 This series is a collection of knowledge about ASP .NET Core. It just is my notes.

Part 1: Startup file.

Part 2: DI.

Part 3: Middleware.

Part 4: Host and Servers.

Part 5: Configurations.

Part 6: Environment.

Part 7: Logs.

Part 8: Error Handling.

Part 10: Make an HTTP Request.

Part 11: Static files.

Part 12: Authentication and Authorization.

Part 13: CORS.

  • Routing is responsible for matching incoming HTTP requests and dispatching those requests to the app's executable endpoints
  • How to use - [From ASP. Net Core 3.0]
public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles();

    // Add the EndpointRoutingMiddleware
    app.UseRouting();

    // All middleware between UseRouting and UseEndpoints will know which endpoint will be invoked
    // can be benerfits from it to do some logical checks
    // For instances:
    app.UseCors();
    app.UseAuthentication();
    app.UseAuthorization();

    // Execute the endpoint selected by the routing middleware
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapDefaultControllerRoute();
    });
}


From "UseRouting" to "UseEndpoints" is called Routing zone, some highlighted points:
  • The endpoint is always null before UseRouting is called.
  • If a match is found, the endpoint is non-null between UseRouting and UseEndpoints.
  • The UseEndpoints middleware is terminal when a match is found.
  • The middleware after UseEndpoints execute only when no match is found.

  • Endpoint routing
            You can attach metadata to endpoints so intermediate middleware (e.g. Authorization, CORS) can know what will be eventually executed For example: MapHealthChecks

app.UseAuthentication();
app.UseAuthorization();

app.MapHealthChecks("/healthz").RequireAuthorization();


How to create a endpoint routing aware:
  • Write an extension method on IEndpointRouteBuilder.
  • Create a nested middleware pipeline using CreateApplicationBuilder.
  • Attach the middleware to the new pipeline.
  • Build the middleware pipeline into a RequestDelegate.
  • Call Map and provide the new middleware pipeline.
  • Return the builder object provided by Map from the extension method.

References:
Share:

0 nhận xét:

Đăng nhận xét

Featured Posts

Data type 3 - string type