.NET Core Documentation

Build a web app with Razor Pages

Razor Pages is a page‑focused framework that makes building web UI easier and more productive. This tutorial walks you through creating, running, and understanding a Razor Pages app using .NET 6+.

Prerequisites

1️⃣ Create a new Razor Pages project

dotnet new webapp -o RazorPagesDemo
cd RazorPagesDemo
dotnet run

The webapp template scaffolds a Razor Pages project with a Pages folder containing sample pages.

2️⃣ Explore the project structure

RazorPagesDemo/
│
├─ Pages/
│   ├─ Index.cshtml          // UI markup
│   ├─ Index.cshtml.cs       // PageModel (code‑behind)
│   ├─ Shared/
│   │   └─ _Layout.cshtml    // common layout
│   └─ _ViewStart.cshtml
│
├─ wwwroot/
│   └─ css/site.css
│
├─ appsettings.json
└─ Program.cs

3️⃣ Understanding Razor Pages

A Razor Page consists of two files:

4️⃣ Adding a new page

dotnet new page -n Contact -o Pages

This creates Contact.cshtml and Contact.cshtml.cs. Open Contact.cshtml and replace its content with:

<h2>Contact us</h2>
<form method="post">
    <div>
        <label asp-for="Message">Message:</label><br/>
        <textarea asp-for="Message" rows="4"></textarea>
    </div>
    <button type="submit">Send</button>
</form>

@if (Model.Sent)
{
    <p>Thank you! Your message was received.</p>
}

And in Contact.cshtml.cs add:

public class ContactModel : PageModel
{
    [BindProperty]
    public string Message { get; set; }
    public bool Sent { get; set; }

    public void OnPost()
    {
        // In a real app, you'd process the message here.
        Sent = true;
    }
}

5️⃣ Run the app again

dotnet run

Navigate to /Contact to see the form in action.

6️⃣ Customizing the layout

Edit Pages/Shared/_Layout.cshtml to change the site header, navigation, or footer.

7️⃣ Deploying

Publish the app with:

dotnet publish -c Release -o ./publish

Then host the contents of publish on any web server that supports ASP.NET Core (Azure App Service, IIS, Nginx, etc.).

Next steps