Build a Blazor movie database app (Part 1 - Create a Blazor Web App)
Note
This isn't the latest version of this article. For the current release, see the .NET 9 version of this article.
Important
This information relates to a pre-release product that may be substantially modified before it's commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
For the current release, see the .NET 9 version of this article.
This article is the first part of the Blazor movie database app tutorial that teaches you the basics of building an ASP.NET Core Blazor Web App with features to manage a movie database.
This part of the tutorial series covers how to create a Blazor Web App that adopts static server-side rendering (static SSR). Static SSR means that content is rendered on the server and sent to the client for display in response to individual requests.
Prerequisites
Visual Studio (latest release) with the ASP.NET and web development workload
Latest releases of:
The Visual Studio Code (VS Code) instructions for ASP.NET Core development in this tutorial use the .NET CLI, which is part of the .NET SDK. .NET CLI commands are issued in VS Code's integrated Terminal, which defaults to a PowerShell command shell. The Terminal is opened by selecting New Terminal from the Terminal menu in the menu bar.
The .NET CLI is part of the .NET SDK. To issue commands that affect the project, open the command shell to the project's root folder.
Create a Blazor Web App
In Visual Studio:
Select Create a new project from the Start Window or select File > New > Project from the menu bar.
In the Create a new project dialog, select Blazor Web App from the list of project templates. Select the Next button.
In the Configure your new project dialog, name the project
BlazorWebAppMovies
in the Project name field, including matching the capitalization. Using this exact project name is important to ensure that the namespaces match for code that you copy from the tutorial into the app that you're building.Confirm that the Location for the app is suitable. Set the Place solution and project in the same directory checkbox to match your preferred solution file location. Select the Next button.
In the Additional information dialog, use the following settings:
- Framework: Select .NET 9.0 (Standard Term Support).
- Authentication type: None
- Configure for HTTPS: Selected
- Interactive render mode: Server
- Interactivity location: Per page/component
- Include sample pages: Selected
- Do not use top-level statements: Not selected
- Select Create.
In the Additional information dialog, use the following settings:
- Framework: Select .NET 8.0 (Long Term Support).
- Authentication type: None
- Configure for HTTPS: Selected
- Interactive render mode: Server
- Interactivity location: Per page/component
- Include sample pages: Selected
- Do not use top-level statements: Not selected
- Select Create.
The Visual Studio instructions in parts of this tutorial series use EF Core commands to add database migrations and update the database. EF Core commands are issued using Visual Studio Connected Services. More information is provided later in this tutorial series.
This tutorial assumes that you have familiarity with VS Code. If you're new to VS Code, see the VS Code documentation. The videos listed by the Introductory Videos page are designed to give you an overview of VS Code's features.
Confirm that you have the latest C# Dev Kit and .NET SDK installed.
In VS Code:
Create a new project:
Go to the Explorer view and select the Create .NET Project button. Alternatively, you can bring up the Command Palette using Ctrl+Shift+P, and then type "
.NET
" to find and select the .NET: New Project command.Select the Blazor Web App project template from the list.
In the Project Location dialog, create or select a folder for the project.
In the Command Palette, name the project
BlazorWebAppMovies
, including matching the capitalization. Using this exact project name is important to ensure that the namespaces match for code that you copy from the tutorial into the app that you're building.Select Create project to create the app.
Confirm that you have the latest .NET SDK installed.
In a command shell:
Use the
cd
command to change to the directory to where you want to create the project folder (for example,cd c:/users/Bernie_Kopell/Documents
).Use the
dotnet new
command with theblazor
project template to create a new Blazor Web App project. The-o|--output
option passed to the command creates the project in a new folder at the current shell directory location. Name the projectBlazorWebAppMovies
, including matching the capitalization, so the namespaces match for code that you copy from the tutorial to the app.dotnet new blazor -o BlazorWebAppMovies
Run the app
Press F5 on the keyboard to run the app.
Visual Studio displays the following dialog when a project isn't configured to use SSL:
Select Yes if you trust the ASP.NET Core SSL certificate.
The following dialog is displayed:
Select Yes to acknowledge the risk and install the certificate.
Visual Studio:
- Compiles and runs the app.
- Launches the default browser at
https://localhost:{PORT}
, which displays the app's UI. The{PORT}
placeholder is the random port assigned to the app when the app is created. If you need to change the port due to a local port conflict, change the port in the project'sProperties/launchSettings.json
file.
Navigate the pages of the app to confirm that the app is working normally.
In VS Code, press F5 to run the app.
At the Select debugger prompt in the Command Palette at the top of the VS Code UI, select C#. At the next prompt, select the default launch configuration (C#: BlazorWebAppMovies [Default Configuration]
).
The default browser is launched at http://localhost:{PORT}
, which displays the app's UI. The {PORT}
placeholder is the random port assigned to the app when the app is created. If you need to change the port due to a local port conflict, change the port in the project's Properties/launchSettings.json
file.
Navigate the pages of the app to confirm that the app is working normally.
In a command shell opened to the project's root folder, execute the dotnet watch
command to compile and start the app:
dotnet watch
The app is compiled and run. The app is launched at http://localhost:{PORT}
, where the {PORT}
placeholder is the random port assigned to the app when the app is created. If you need to change the port due to a local port conflict, change the port in the project's Properties/launchSettings.json
file.
Navigate the pages of the app to confirm that the app is working normally.
Stop the app
Stop the app using either of the following approaches:
- Close the browser window.
- In Visual Studio, either:
Use the Stop button in Visual Studio's menu bar:
Press Shift+F5 on the keyboard.
Stop the app using the following approach:
- Close the browser window.
- In VS Code, either:
- From the Run menu, select Stop Debugging.
- Press Shift+F5 on the keyboard.
Stop the app using the following approach:
- Close the browser window.
- In the command shell, press Ctrl+C (Windows) or ⌘+C (macOS).
Examine the project files
The following sections contain an overview of the project's folders and files.
If you're building the app, you don't need to make changes to the project files in the following sections. As you read the descriptions of the folders and files, examine them in the project.
If you're only reading the articles and not building the app, you can refer to the completed sample app in the Blazor samples GitHub repository (dotnet/blazor-samples
). Select the latest version folder in the repository. The sample folder for this tutorial's project is named BlazorWebAppMovies
. The sample app is the finished version of the app after following all of the steps of the tutorial series. Code in the sample doesn't always match steps of the tutorial before the end of the series.
Properties
folder
The Properties
folder holds development environment configuration in the launchSettings.json
file.
wwwroot
folder
The wwwroot
folder contains static assets, such as image, JavaScript (.js
), and stylesheet (.css
) files.
Components
, Components/Pages
, and Components/Layout
folders
These folders contain Razor components, often referred to as "components," and supporting files. A component is a self-contained portion of user interface (UI) with optional processing logic. Components can be nested, reused, and shared among projects.
Components are implemented using a combination of C# and HTML markup in Razor component files with the .razor
file extension.
Typically, components that are nested within other components and not directly reachable ("routable") at a URL are placed in the Components
folder. Components that are routable via a URL are usually placed in the Components/Pages
folder.
The Components/Layout
folder contains the following layout components and stylesheets:
MainLayout
component (MainLayout.razor
): The app's main layout component.MainLayout.razor.css
: Stylesheet for the app's main layout.NavMenu
component (NavMenu.razor
): Implements sidebar navigation. This component uses severalNavLink
components to render navigation links to other Razor components.NavMenu.razor.css
: Stylesheet for the app's navigation menu.
Components/_Imports.razor
file
The _Imports
file (_Imports.razor
) includes common Razor directives to include in the app's Razor components. Razor directives are reserved keywords prefixed with @
that appear in Razor markup and change the way component markup or component elements are compiled or function.
Components/App.razor
file
The App
component (App.razor
) is the root component of the app that includes:
- HTML markup.
- The
Routes
component. - The Blazor script (
<script>
tag forblazor.web.js
).
The root component is the first component that the app loads.
Components/Routes.razor
file
The Routes
component (Routes.razor
) sets up routing for the app.
appsettings.json
file
The appsettings.json
file contains configuration data, such as connection strings.
Warning
Don't store app secrets, connection strings, credentials, passwords, personal identification numbers (PINs), private C#/.NET code, or private keys/tokens in client-side code, which is always insecure. In test/staging and production environments, server-side Blazor code and web APIs should use secure authentication flows that avoid maintaining credentials within project code or configuration files. Outside of local development testing, we recommend avoiding the use of environment variables to store sensitive data, as environment variables aren't the most secure approach. For local development testing, the Secret Manager tool is recommended for securing sensitive data. For more information, see Securely maintain sensitive data and credentials.
Program.cs
file
The Program.cs
file contains code to create the app and configure the request processing pipeline of the app.
The order of the lines in the Blazor Web App project template changes across releases of .NET, so the order of the lines in the Program.cs
file might not match the order of the lines covered in this section.
A WebApplicationBuilder creates the app with preconfigured defaults:
var builder = WebApplication.CreateBuilder(args);
Razor component services are added to the app by calling AddRazorComponents, which enables Razor components to render and execute code on the server, and AddInteractiveServerComponents adds services to support rendering Interactive Server components:
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
The WebApplication (held by the app
variable in the following code) is built:
var app = builder.Build();
Next, the HTTP request pipeline is configured.
In the development environment:
- Exception Handler Middleware (UseExceptionHandler) processes errors and displays a developer exception page during development app runs.
- HTTP Strict Transport Security Protocol (HSTS) Middleware (UseHsts) processes HSTS.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
app.UseHsts();
}
HTTPS Redirection Middleware (UseHttpsRedirection) enforces the HTTPS protocol by redirecting HTTP requests to HTTPS if an HTTPS port is available:
app.UseHttpsRedirection();
Antiforgery Middleware (UseAntiforgery) enforces antiforgery protection for form processing:
app.UseAntiforgery();
Map Static Assets routing endpoint conventions (MapStaticAssets) maps static files, such as images, scripts, and stylesheets, produced during the build as endpoints:
app.MapStaticAssets();
Static File Middleware (UseStaticFiles) serves static files, such as images, scripts, and stylesheets from the wwwroot
folder:
app.UseStaticFiles();
MapRazorComponents maps components defined in the root App
component to the given .NET assembly and renders routable components, and AddInteractiveServerRenderMode configures interactive server-side rendering (interactive SSR) support for the app:
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
Note
The extension methods AddInteractiveServerComponents on AddRazorComponents and AddInteractiveServerRenderMode on MapRazorComponents make the app capable of adopting interactive SSR, which isn't relevant until the last part of the tutorial series on interactivity. Over the next several articles, the app's components only adopt static SSR.
The app is run by calling Run on the WebApplication (app
):
app.Run();
Troubleshoot with the completed sample
If you run into a problem while following the tutorial that you can't resolve from the text, compare your code to the completed project in the Blazor samples repository:
Blazor samples GitHub repository (dotnet/blazor-samples
)
Select the latest version folder. The sample folder for this tutorial's project is named BlazorWebAppMovies
.
Additional resources
When using VS Code or the .NET CLI, this tutorial series adopts insecure HTTP protocol to ease the transition of adopting SSL/HTTPS security for Linux and macOS users. For information on adopting SSL/HTTPS, see Enforce HTTPS in ASP.NET Core.
Next steps
ASP.NET Core