Home
C#.ASP.NET
MapRazorPages Example
Updated May 26, 2023
Dot Net Perls
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.
Notes, endpoints. 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 example. To begin, open the Startup file and locate the ConfigureServices and Configure methods. We need to add 2 method calls to this file.
Configure
Part 1 Add a call to AddRazorPages() in the ConfigureServices method. This is needed to use Razor pages.
Part 2 Now add a call to MapRazorPages in the UseEndpoints lambda expression. This can be in addition to a MapGet call.
MapGet
Part 3 Here we have a Razor page called "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 application. Run 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.
Tip No extension is needed to go from "Hello" to "Hello.cshtml." The extension is automatically resolved by ASP.NET Core.
An important note. 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.
A summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
No updates found for this page.
Home
Changes
© 2007-2025 Sam Allen