Home
Map
C#.ASP.NET
MapRazorPages Example
This page was last reviewed on 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2024 Sam Allen.