MapRazorPages registers the endpoints for an application's Razor Pages. With Razor Pages services configured and the request pipeline built, it lets ASP.NET Core route requests to pages and generate HTML responses. section 13.1.2
Endpoint mapping connects incoming URLs to Razor Page handlers:
- MapRazorPages creates a route template for each Razor Page from its path under the Pages/ directory, excluding the .cshtml extension. section 14.3
- RoutingMiddleware selects a matching endpoint, then EndpointMiddleware executes the selected page and its handler; unmatched URLs produce no endpoint response. section 14.1 section 14.3
- A page at Pages/Products/View.cshtml matches /products/view, while Pages/ToDo/Index.cshtml matches both /ToDo and /ToDo/Index. section 14.3
Registering Razor Page endpoints
Configure Razor Pages services, build the application, and call app.MapRazorPages() in Program.cs after the routing-related middleware. The application can then match requests to Razor Pages and invoke their handlers. section 13.1.2 section 14.1
Listing 13.2 The Program.cs file for a Razor Pages app
WebApplicationBuilder builder = WebApplication.CreateBuilder(args); builder.Services.AddRazorPages(); #1 WebApplication app = builder.Build(); if (!app.Environment.IsDevelopment()) #2 { #2 app.UseExceptionHandler("/Error"); #2 app.UseHsts() #2 } #2 app.UseHttpsRedirection(); #3 app.UseStaticFiles(); #3 app.UseRouting(); #3 app.UseAuthorization(); #3 app.MapRazorPages(); #4 app.Run(); #1 Registers the required services to use the Razor Pages feature #2 Conditionally adds middleware depending on the runtime environment #3 Additional middleware can be added to the middleware pipeline. #4 Registers each Razor Page as an endpoint in your application
Use the complete Program.cs listing to see AddRazorPages, middleware configuration, and MapRazorPages together in a runnable application. section 13.1.2
