In this article, we will explore the files and folders that make up a Blazor app generated from a Blazor project template. We will compare and contrast the project structure of Blazor Server and Blazor WebAssembly, and explain the purpose and function of each file and folder.
We will also learn how to configure the app settings, the routing, and the rendering modes for Blazor apps.
By the end of this article, you will have a better understanding of the Blazor project structure and how to organize your Blazor app.
Read: Installing Blazor
Template: Blazor Web App
Server Project:
This is the main project where the server-side code resides.
Components folder:
The Components folder is a folder that contains the app’s Razor components. Razor components are reusable and can be nested, shared, and used in other types of ASP.NET Core apps. For example, you might have a Login.razor component that contains the markup and logic for a login form that you can use on multiple pages of your app.
1. Layout folder:
The Components folder also contains a Layout folder, which is a subfolder that contains the layout components and stylesheets for your app. Layout components are Razor components that define the common UI elements for your app, such as the header, footer, and navigation menu. Layout components can be applied to one or more pages of your app using the @layout directive. Stylesheets are CSS files that define the appearance and formatting of your app.
The Layout folder contains the following files:
MainLayout.razor: This is the main layout component for your app. It typically includes elements like the header, footer, and navigation menu that are common across all pages. It also uses the Body parameter to render the content of each page.
MainLayout.razor.css: This is the stylesheet for the main layout component. It contains the CSS rules that style the elements in the MainLayout.razor component, such as the background color, font size, and margin.
NavMenu.razor: This component implements the sidebar navigation for your app. It might contain links to the different pages in your app using the NavLink component, which is a built-in component that renders navigation links to other Razor components and indicates the selected state.
NavMenu.razor.css: This is the stylesheet for the navigation menu component. It contains the CSS rules that style the NavMenu.razor components, such as the width, color, and hover effect.
2. Pages folder:
The Pages folder is a folder that contains the app’s routable server-side Razor components. Routable components are components that can be accessed by a URL, such as /counter or /weather. The Pages folder contains the following components:
Counter.razor: This component implements the Counter page, which demonstrates user interaction and state management. It has a button that increments a value when clicked, and displays the current count.
Error.razor: This component implements the Error page, which is displayed when there is an unhandled exception or when a requested route does not match any component. It shows an error message and a stack trace.
Home.razor: This component implements the Home page, which is typically the first page users see when they visit your app. It displays a welcome message and a link to the Counter page.
Weather.razor: This component implements the Weather forecast page, which demonstrates data loading and display. It loads data from a static asset (weather.json) and displays it in a table.
3. App.razor:
The App.razor file is the root component of the app, which is the first component that the app loads. The App.razor file sets up the routing for the app using the Router component, which is a built-in component that handles navigation and rendering of pages based on the URL. The Router component has the following parameters:
AppAssembly: The assembly that contains the app’s components.
Found: A template that renders when a matching page is found for the requested URL. The template receives a parameter named routeData, which contains information about the matched page and its parameters.
NotFound: A template that renders when no matching page is found for the requested URL.
OnNavigateAsync: A callback that runs before navigation occurs. You can use this to perform asynchronous logic, such as authentication or data loading, and cancel or redirect the navigation.
4. Routes.razor:
This file configures the routing for your app using the Router component1, which is a built-in component that handles navigation and rendering of pages based on the URL. The Router component takes an AppAssembly parameter that specifies the assembly that contains your app’s components. The Router component also has Found and NotFound templates that define what to render when a matching or non-matching page is found for the requested URL. The Router component uses the Route components inside the Routes.razor file to map the paths to the Razor components.
Each Route component has a Path parameter that specifies the route template and a Component parameter that specifies the Razor component to render for that path. For example, the following Route component maps the path “/counter” to the Counter.razor component:
<Route Path="/counter" Component="typeof(Counter)" />
5. _Imports.razor:
This file includes common Razor directives3 to include in the app’s components (.razor), such as @using directives for namespaces. Razor directives are special keywords that start with the @ symbol and provide instructions to the Razor compiler. For example, the following directive adds the System namespace to the components:
@using System
The Imports.razor file is similar to the ViewImports.cshtml file for Razor views and pages but applied specifically to Razor component files.
Properties folder:
This folder holds development environment configuration in the launchSettings.json file4. This file contains settings for launching and debugging the app, such as the application URL, the environment variables, and the browser to use.
For example, the following settings launch the app on port 5001 using HTTPS and set the ASPNETCORE_ENVIRONMENT variable to Development:
{
"profiles": {
"BlazorApp1": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Program.cs file:
The Program.cs file is the server project’s entry point, which sets up the ASP.NET Core web application host and contains the app’s startup logic. The Program.cs file does the following:
It creates an instance of the WebHostBuilder class, which provides methods to configure the host, such as setting the content root, the environment, and the web server.
It calls the UseStartup<Startup> method, which specifies the Startup class to be used by the web host. The Startup class contains methods to configure the services and the middleware for the app.
It calls the Build and Run methods, which build and run the host.
The Program.cs file also contains some methods that are specific to Blazor WebAssembly, which is a feature of ASP.NET Core that lets you create web apps with C# and .NET without writing JavaScript. Blazor WebAssembly can run in two modes: interactive SSR and interactive WebAssembly.
Interactive SSR mode: In this mode, the Razor components are rendered on the server and streamed to the browser as HTML. The browser then establishes a SignalR connection with the server and sends user events back to the server, such as clicks and keystrokes. The server updates the UI and sends the changes back to the browser. This mode provides fast initial load time and SEO benefits, but requires a persistent connection and more server resources.
Interactive WebAssembly mode: In this mode, the Razor components are compiled to WebAssembly and downloaded to the browser. The browser then runs the WebAssembly code using a .NET runtime and renders the UI. The browser can also communicate with the server using HTTP or SignalR to fetch data or perform other operations. This mode provides better performance and offline support, but requires a larger download size and longer initial load time.
The Program.cs file contains the following methods to configure the Blazor WebAssembly modes:
AddRazorComponents: This method adds the services required by the Razor components, such as HttpClient, NavigationManager, and ComponentServiceCollection.
AddInteractiveServerComponents: This method adds the services to support rendering interactive server components, such as CircuitHandler, CircuitFactory, and RemoteRenderer.
AddInteractiveWebAssemblyComponents: This method adds the services to support rendering interactive WebAssembly components, such as WebAssemblyHost, WebAssemblyJSRuntime, and WebAssemblyComponentSerializer.
MapRazorComponents: This method discovers the available components in the app and specifies the root component for the app, which is the first component that the app loads. By default, the root component is the App component (App.razor), which sets up the routing for the app.
AddInteractiveServerRenderMode: This method configures the interactive SSR mode for the app. It takes a parameter that specifies the path to the root component, such as “/_blazor”. It also registers a middleware that handles the requests to the root component and renders the interactive server components.
AddInteractiveWebAssemblyRenderMode: This method configures the interactive WebAssembly mode for the app. It takes a parameter that specifies the path to the WebAssembly resources, such as “/_framework”. It also registers a middleware that handles the requests to the WebAssembly resources and serves the interactive WebAssembly components.
The Program.cs file also contains the app settings files (appsettings.Development.json, appsettings.json), which provide configuration settings for the server project, such as the logging level, the connection strings, and the API endpoints.
Client project (.Client):
The Client project (.Client) is a project that contains the files and folders for the client-side part of your Blazor WebAssembly app. Blazor WebAssembly is a feature of ASP.NET that lets you create web apps with C# and .NET without writing JavaScript.
The client project has the following files and folders:
Pages
wwroot
Program.cs
_Imports.razor
Template: Blazor WebAssembly
Blazor WebAssembly uses a WebAssembly-based .NET runtime that runs in the browser.
When you create a new Blazor WebAssembly project, you can choose from different templates that provide a starting point for your app. The blazorwasm template is the default one, and it creates a standalone Blazor WebAssembly app that doesn’t depend on a server-side backend.
The blazorwasm template creates the following files and directories:
wwwroot: This folder contains the static files that are served by the web server, such as HTML, CSS, JavaScript, and images. It also contains a weather.json file that is used by the Weather component to load data.
Pages: This folder contains the Razor components that define the pages of the app, such as Index.razor, Counter.razor, and FetchData.razor. Razor components are files with the .razor extension that combine HTML and C# code to render dynamic UI.
Shared: This folder contains the Razor components that are shared by multiple pages, such as MainLayout.razor, NavMenu.razor, and SurveyPrompt.razor.
App.razor: This file defines the root component of the app, which handles routing and rendering of the pages.
Program.cs: This file contains the C# code that initializes and configures the app.
blazor.webconfig: This file contains the web server settings for the app, such as the MIME types for WebAssembly files and the URL rewrite rules.
The blazorwasm template also includes some demonstration code that shows how to use Blazor features, such as:
A Weather component that loads data from a static asset (weather.json) and displays it in a table.
A Counter component that increments a value when a button is clicked and demonstrates user interaction and state management.
A Bootstrap frontend toolkit that provides styling and layout for the app.
The blazorwasm template can also be generated without sample pages and styling by using the --no-https option when creating the project. This option removes the demonstration code and the Bootstrap dependency, and creates a minimal Blazor WebAssembly app with only an Index.razor page and a MainLayout.razor component.
Structure of project
Your project has the following folders and files:
Layout folder:
This folder contains the layout components and stylesheets for your app. The layout components are Razor components that define the common UI elements for your app, such as the header, footer, and navigation menu. The stylesheets are CSS files that define the appearance and formatting of your app.
MainLayout.razor: This is the app’s layout component, which defines the main structure of your app. It uses the NavMenu component to render the sidebar navigation, and the Body parameter to render the content of each page.
MainLayout.razor.css: This is the stylesheet for the app’s main layout, which defines the styles for the layout component and its elements.
NavMenu.razor: This component implements the sidebar navigation for your app. It uses the NavLink component to render the navigation links to other Razor components. The NavLink component automatically indicates a selected state when its component is loaded, which helps the user understand which component is currently displayed.
NavMenu.razor.css: This is the stylesheet for the app’s navigation menu, which defines the styles for the navigation component and its elements.
Pages folder:
This folder contains the Blazor app’s routable Razor components, which define the pages of your app. The route for each page is specified using the @page directive, which tells the Router component how to match the requested URL to the component.
The template includes the following components:
Counter.razor: This component implements the Counter page, which demonstrates user interaction and state management. It has a button that increments a value when clicked, and displays the current count.
Index.razor: This component implements the Home page, which displays a welcome message and a link to the Counter page.
Weather.razor: This component implements the Weather page, which demonstrates data loading and display. It loads data from a static asset (weather.json) and displays it in a table.
_Imports.razor:
The Imports.razor file is a file that contains common Razor directives that apply to all the Razor components in your app. Razor directives are special instructions that start with the @ symbol and affect how the Razor engine processes the component.
For example, the @using directive imports a namespace so that you can use its types without specifying the full name. By adding the @using directives to the Imports.razor file, you can avoid repeating them in every component file.
You can also add other directives, such as @inject, @layout, or @attribute, to the _Imports.razor file.
App.razor:
The App.razor file is the root component of your app, which is the first component that the app loads. The App.razor file sets up client-side routing using the Router component, which is a built-in component that handles navigation and rendering of pages based on the URL.
Properties folder:
The Properties folder is a folder that holds development environment configuration in the launchSettings.json file. This file defines the settings for launching the app, such as the URL, port, and protocol, for different profiles.
For example, the default profile launches the app using HTTPS on port 5001, while the IIS Express profile launches the app using IIS Express on port 44300. You can modify the launchSettings.json file to change the launch settings or add new profiles.
wwwroot folder:
The wwwroot folder is the web root folder for your app, which means it contains the public static files that are served by the web server, such as HTML, CSS, JavaScript, and images. The wwwroot folder also contains the appsettings.json file and the environmental app settings files, which store the configuration settings for your app, such as the base URL, the logging level, and the API endpoints. Additionally, the wwwroot folder contains a sample weather data file (sample-data/weather.json), which is used by the Weather component to load and display data.
The index.html file is the root page of your app, which is the HTML file that is returned when any page of your app is initially requested. The index.html file specifies where the root App component is rendered, which is the div DOM element with an id of app (<div id=“app”>Loading…</div>). The App component is the main component of your app, which handles routing and rendering of the pages.
Program.cs:
The Program.cs file is the app’s entry point, which sets up the WebAssembly host. The WebAssembly host is the object that configures and runs your app in the browser using a WebAssembly-based .NET runtime. The Program.cs file does the following:
It creates an instance of the WebAssemblyHostBuilder class, which provides methods to configure the host.
It adds the App component as the root component of the app, and specifies the div DOM element with an id of app as the location to render it (builder.RootComponents.Add<App>(“#app”)).
It adds and configures the services that are used by the app, such as HttpClient, NavigationManager, and IMyDependency (for example, builder.Services.AddSingleton<IMyDependency, MyDependency>()).
It builds and runs the host using the Build and Run methods.
Conclusion
In this article, we have explored the files and folders that make up a Blazor app generated from a Blazor project template. We have compared and contrasted the project structure of Blazor Server and Blazor WebAssembly, and explained the purpose and function of each file and folder. We have also learned how to configure the app settings, the routing, and the rendering modes for Blazor apps.
Comments