MapRazorPages
When creating an empty ASP.NET Core Web Application, we must figure out how to add endpoints for Razor pages. Otherwise we cannot open Razor pages in the browser.
We do not need to add specific MapGet
calls for Razor pages in an ASP.NET Core Web Application. Instead, these are all handled automatically.
Configure
exampleTo begin, open the Startup file and locate the ConfigureServices
and Configure
methods. We need to add 2 method calls to this file.
AddRazorPages()
in the ConfigureServices
method. This is needed to use Razor pages.MapRazorPages
in the UseEndpoints
lambda expression. This can be in addition to a MapGet
call.Hello.cshtml
" and we must place it in a Pages folder in the ASP.NET Core Web Application project.using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace WebApplication6 // Date: 3/25/2020. { public class Startup { public void ConfigureServices(IServiceCollection services) { // Part 1: add this call. services.AddRazorPages(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(endpoints => { // Part 2: add this call. endpoints.MapRazorPages(); }); } } }@page @{ @* Part 3: add some razor syntax to Pages/Hello.cshtml *@ <h1>Hello friend</h1> for (int i = 0; i < 5; i++) { <p>Number: @i</p> } }
Result
, run applicationRun the website in Visual Studio and it will return a 404 error. But then go to "Hello" by specifying the URL in the browser, and the Razor page will render.
We must place the "Hello.cshtml
" file in a Pages folder in the ASP.NET Core Web Application project. Otherwise, MapRazorPages
will not work correctly.
We made AddRazorPages
and MapRazorPages
work correctly in an ASP.NET Core Web Application. We went from an Empty web application to one that renders Razor pages.