Blazor is a framework for building modern, interactive web-based UIs with C# and Razor.

Browser + Razor = Blazor

Blazor is completely an open source project from ASP.NET team. The source code is available at : https://github.com/dotnet/aspnetcore/tree/master/src/Components

This post is part of a series of blog posts on blazor. In this, let’s start with gaining the initial understanding on

  1. Different use cases where blazor can be used
  2. Various hosting models that blazor supports
  3. Getting started
    1. Blazor Server app
    2. Blazor WebAssembly app

If you are a .NET developer for the past few years, you would already be exposed to MVC and Razor Pages at some point in time. Below section details about the comparison of these workloads. If you are completely new to dotnet, feel free to skip the below section and head over to the Hosting models

So, where does blazor fit, as ASP.NET Core already has MVC and Razor Pages ??

MVC – Model View Controller helped in building web applications that runs on the server; browser just gets the HTML for the new page to load and it just displays the same. The View part would be handled in .cshtml file and the business logic would be handled in Controller (that loads the data to be bound to view)

Razor Pages – With ASP.NET Core, Razor pages were launched where instead of using full blown Model/View/Controller, the view part was taken care by the code in .cshtml file and the associated business logic was handled by its corresponding .cshtml.cs file. This can be thought of like a light-weight MVC without a real controller in place.

Blazor is primarily a SPA (Single Page Application) Framework that means it is mainly used to handle interactive applications at client side. Other popular SPA frameworks are Angular, ReactJs, VueJs etc., to name a few. The major difference between Blazor and other SPA frameworks is that the entire client side view and the interaction can technically be handled without using any JavaScript but completely in C# and Razor. Below table highlights some of the key differences between these various workloads

FeatureMVCRazor PagesBlazor
RenderingServer sideServer sideServer side & Client side
ViewRazor syntax in .cshtml fileRazor syntax in .cshtml fileRazor syntax in .razor file
Business logicController fileC# code behind in .cshtml.cs file1. Can be written directly in .razor file
2. Can be written in .razor.cs file
Page based approachYesYesNo
Components based approachNoNoYes
Hosting modelsASP.NET Core hosted ASP.NET Core hosted1. ASP.NET Core hosted (Server side app)
2. ASP.NET Core hosted (Client side app)
3. Webassembly (WASM) based – pure client side app
AuthorizationHandled at server sideHandled at server sideYes. Depends on hosting model

Blazor Hosting models

Before we get into the actual creation of first blazor app, let’s understand the various hosting models blazor supports. This would help in choosing the right fit for the need

Blazor Server :
  • Blazor server apps are hosted within ASP.NET Core process
  • The components are rendered in the server and the incremental DOM changes are transmitted over SignalR connection to the client
  • An Active connection between the browser and the server is MANDATORY for this hosting model

Image from : https://docs.microsoft.com/en-us/aspnet/core/blazor/hosting-models/_static/blazor-server.png?view=aspnetcore-5.0

Blazor Web Assembly :
  • Blazor is built on an open web standard called Web Assembly (https://webassembly.org/)
  • Web Assemblies help in running the .NET DLLs directly within the browser. There is no transpilation or any code conversion that happens in this case. C# code would be targeted to run on top of dotnet.wasm runtime.
  • All the DLLs are downloaded at the app start to the browser and then depending on the code execution, the appropriate dlls would be consumed

Image from : https://docs.microsoft.com/en-us/aspnet/core/blazor/hosting-models/_static/blazor-webassembly.png?view=aspnetcore-5.0

Comparison between blazor Server and webassembly apps

Hosting modelProsCons
Blazor Server– Full advantage of server side capabilities of .NET Core

– Download size is smaller; hence faster app load

– Better Tooling and Debugging support
– Active connection to server is needed; No offline support

– High latency due to continuous connection to server for every client action

– Dependency on ASP.NET Core for hosting the apps
Blazor Webassembly– No .NET dependency on server side

– Offline capabilities are possible, as everything is run on the browser

– App can be deployed to static storage or CDN and served from there
– Initial load time would be more as all the components should be downloaded at app startup

– Runs only on browsers that support Web Assembly

– Tooling and Debugging support is sub-par (at the time of this writing)

Getting Started

Prerequisites:

  1. Latest dotnet sdk (.NET 5.0 at the time of this writing) – Download and install from dot.net
  2. Visual Studio Code – Download and install from code.visualstudio.com
    1. C# extension for VS Code- Download and install from https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp
  3. Visual Studio for Windows/Mac – Download and install from https://visualstudio.microsoft.com/

Either (2) or (3) is needed for local development and testing of blazor apps. In this post, I will be using VS Code + C# extension.

Creating a new blazor server app :

  1. Open Terminal on Mac/Windows and run the below command to check the dotnet installation.
❯ dotnet --version
5.0.101

2. Use the dotnet CLI’s templates to create a new blazor app.

For Blazor server app, run the below command

❯ dotnet new blazorserver -o first-server-app
The template "Blazor Server App" was created successfully.
This template contains technologies from parties other than Microsoft, see https://aka.ms/aspnetcore/5.0-third-party-notices for details.

Processing post-creation actions...
Running 'dotnet restore' on first-server-app/first-server-app.csproj...
  Determining projects to restore...
  Restored /Users/swami/Projects/dotnet/blazor/first-server-app/first-server-app.csproj (in 55 ms).
Restore succeeded.

3. Open the project in VS Code using the below commands

❯ cd first-server-app
❯ code .

4. Understand the project structure

  • Startup.cs -> Contains the necessary code for bootstrapping the blazor server app. ConfigureServices method have a new service method called AddServerSideBlazor which will let ASP.NET core to inject blazor service

     public void ConfigureServices(IServiceCollection services)
            {
                services.AddRazorPages();
                services.AddServerSideBlazor();
                services.AddSingleton<WeatherForecastService>();
            }
    

    Another important code snippet to understand is the below one (especially line #3) which sets up the SignalR hub

     app.UseEndpoints(endpoints =>
                {
                    endpoints.MapBlazorHub();
                    endpoints.MapFallbackToPage("/_Host");
                });
    
  • Program.cs – Defines the entrypoint to the app and instructs which Startup class to be used to start the ASP.NET core application. Below is the code from the same

     public static void Main(string[] args)
            {
                CreateHostBuilder(args).Build().Run();
            }
    
            public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.UseStartup<Startup>();
                    });
    
  • first-server-app.csproj – Project file which contains the project metadata, installed nuget packages and other details. Note the project type of this app as mentioned below, its just .NET web app.

    <Project Sdk="Microsoft.NET.Sdk.Web">
    
  • appsettings.json – Configuration file used to define app settings

  • App.razor – Main component that defines the router and the default Layout to be used by the entire blazor app

  • _Imports.razor – This is where all the dependencies that are to be used by different components within the app need to be defined.

  • wwwroot – All the static files and assets (images/data/css/js/ etc.,) go here

  • Shared/ – This folder hosts all the shared components. In the brand new app created using dotnet cli, there would be 3 main components

    1. MainLayout – this defines the overall layout of the application
    2. NavMenu – this defines the navigation menu present in the application
    3. SurveyPrompt – a custom reusable razor component that would be used in another page in the app
  • Pages/ – This folder hosts all the different pages within the application. A page could be made up of multiple razor components or just razor syntax with attached code behind in it. With the new project template, below files would be present within the folder

    1. _Host.cshtml – This is the host page (built as a Razor page) where the blazor components are initialized. The below line of code does the component activation. Here, the App.razor component is getting Prerendered at server.
    <component type="typeof(App)" render-mode="ServerPrerendered" />
    

    Another important line of code to understand in this file is the below one, which helps in establishing the SignalR connection between browser and the server

    <script src="_framework/blazor.server.js"></script>
    

    2. Counter.razor – Counter page implementation

    3. FetchData.razor – Fetch Data page

    4. Index.razor – Landing page of the app

5. Run the blazor server app

To run the blazor server app, run the command. This will open the application in your default browser, watch for any changes to the code file and reload the application in the browser

dotnet watch run

Creating a new blazor webassembly app:

  1. Run the below command in terminal
❯ dotnet new blazorwasm -o first-wasm-app
The template "Blazor WebAssembly App" was created successfully.
This template contains technologies from parties other than Microsoft, see https://aka.ms/aspnetcore/5.0-third-party-notices for details.

Processing post-creation actions...
Running 'dotnet restore' on /Users/swami/Projects/dotnet/blazor/first-wasm-app/first-wasm-app.csproj...
  Determining projects to restore...
  Restored /Users/swami/Projects/dotnet/blazor/first-wasm-app/first-wasm-app.csproj (in 305 ms).
Restore succeeded.

2. Exploring the blazorwebassembly app

Run the below commands as before and open the project in VS Code

❯ cd first-wasm-app
❯ code .

I would be highlighting just the differences w.r.t hosting in the webassembly project structure as the components structure remains the same in both the workloads

  • Program.cs – Looking at the main method, you could notice the below lines of highlighted code, that enables the webassembly version

    public static async Task Main(string[] args)
            {
                var builder = WebAssemblyHostBuilder.CreateDefault(args);
                builder.RootComponents.Add<App>("#app");
    
                builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
    
                await builder.Build().RunAsync();
            }
    

    also note, there is NO Startup.cs file as that’s needed only for ASP.NET Core apps. Web assembly apps run directly in browser outside of ASP.NET core process completely

  • first-wasm-app.csproj – Project file that defines the metadata. This also has additional Items than the server side app. Also, notice the change in the project type

    <Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
    
      <PropertyGroup>
        <TargetFramework>net5.0</TargetFramework>
      </PropertyGroup>
    
      <ItemGroup>
        <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="5.0.1" />
        <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="5.0.1" PrivateAssets="all" />
        <PackageReference Include="System.Net.Http.Json" Version="5.0.0" />
      </ItemGroup>
    
    </Project>
    

Other than these two changes, pretty much the component implementation would be similar in both the cases. More details on creating components, routing and other concepts would be discussed in detail in the subsequent posts

Recap :

In this post, we learnt

  • Where does Blazor fit in the overall ASP.NET ecosystem of web apps
  • What are the different hosting models for blazor and their pros and cons
  • Getting started with blazor server and blazor webassembly app