ASP.NET Core 5.0 : MVC, Razor Pages, Web API, EF Core, Blazor, Design Patterns, and more. Private online coaching for software developers. Click here for more details.

Setup Blazor app using ASP.NET Core Empty project template (Part 2)

In Part 1 of this article, you learned to setup a Blazor Server app using ASP.NET Core's empty project template. Continuing further, this part teaches you to prepare a Blazor WebAssembly app using an empty project template. Since you are familiar with the basics outlined in the previous part, let's get going by creating a new empty project in Visual Studio.

In our first example of this article, we will create a standalone Blazor WebAssembly app and then we will create an ASP.NET Core hosted Blazor WebAsselbly app.

Once you create an ASP.NET Core empty project, first thing you need to do is change the project's SDK to Microsoft.NET.Sdk.BlazorWebAssembly. For a standard ASP.NET Core app the SDK is Microsoft.NET.Sdk.Web. To make this change, open .csproj project in Visual Studio and change it as shown below:

<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
...
...
</Project>

Notice the SDK marked in bold letters.

Now you need to add two NuGet packages to the project:

  • Microsoft.AspNetCore.Components.WebAssembly
  • Microsoft.AspNetCore.Components.WebAssembly.DevServer

The following figure shows these NuGet packages installed in the empty project. 

Now add the Pages folder, Shared folder, App.razor, and _Imports.razor exactly as discussed in Part 1 of this article. These files remain unchanged even for Blazor WebAssembly app.

Then delete _Host.cshtml file from the Pages folder. This file is needed only for Blazor Server app. For Blazor WebAssembly app you need to add an HTML file named Index.html in the wwwroot folder. So, create wwwroot folder under project root and then add Index.html file in it. 

Then add the following markup in Index.html file.

<!DOCTYPE html>
<html>

<head>
    <base href="/" />
</head>

<body>
    <div id="app">Loading...</div>
    <script src="_framework/blazor.webassembly.js"></script>
</body>
</html>

Since we are creating a Blazor WebAssembly app the <script> tag references blazor.webassembly.js file.

Next, delete the Startup.cs file from the project root. This file is required for ASP.NET Core applications and Blazor Server app. For Blazor WebAssembly we will modify Program.cs file as shown below:

public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    builder.RootComponents.Add<App>("#app");

    await builder.Build().RunAsync();
}

As you can see, we used WebAssemblyHostBuilder to creatte a builder and added App root component using builder.RootComponents.Add() method. Note that #app is the ID of the <div> element that we added to Index.html page. This acts as a marker for loading the root component.

At this stage your Solution Explorer should resemble this:

Save all the open files and hit F5 to run the application. Here is a sample output.

If you are using ASP.NET Core's development web server to run the app, you won't find any problem in getting the output shown above. In case you are using IIS Express, you might get this error:

To quickly fix this error for IIS Express, add this to your project file:

...
<PropertyGroup>
  <TargetFramework>net6.0</TargetFramework>
  <AspNetCoreHostingModel>
       OutOfProcess
  </AspNetCoreHostingModel>
</PropertyGroup>
...

As you can see, specifying ASP.NET Core hosting model to be OutOfProcess should fix the issue and your app will run as expected (I won't go into the details of this error since that's not of our interest in this article).

So far so good. We just create a standalone Blazor WebAssembly app. What if you want to create a Blazor WebAssembly app that is hosted in an ASP.NET Core app? In such case your Blazor WebAssembly app is served by the ASP.NET Core web application.

Let's understand how to configure that also.

Add another ASP.NET Core empty web application in the same solution. That means you have two projects now - Blazor WebAssembly standalone project and newly added empty web application (see below).

After adding new the empty web application set that app as the startup project. As you can see from the figure, the second project appears in bold letters indicating that it is the startup project. You need to do this because ASP.NET Core web app will now be serving a Blazor WebAssembly app to the browser.

In a more realistic case this second web application will contain Web APIs and other server side resources that are required by Blazor WebAssembly app. We won't have them here just to keep things simple.

Next, add a NuGet package for Microsoft.AspNetCore.Components.WebAssembly.Server in the ASP.NET Core web app project.

Also add a project reference to the Blazor WebAssembly app you created earlier. This can be done by right clicking on the Dependencies and then selecting Add Project Reference from the shortcut menu. Doing so will open this dialog:

Select the Blazor WebAssembly project and click OK.

Now open the Startup class and modify the ConfigureServices() method as shown below:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddRazorPages();
}

Then proceed to modify the Configure() method as follows:

public void Configure(IApplicationBuilder app, 
IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseBlazorFrameworkFiles();

    app.UseStaticFiles();

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapControllers();
        endpoints.MapFallbackToFile("index.html");
    });
}

As you can see, we called UseBlazorFrameworkFiles() method so that Blazor app can be served to the browser. We also configured the routing for the application. Recollect that for Blazor Server app we specified _Host file using MapFallbackToPage() method and here we are specifying Index.html file using MapFallbackToFile() method.

This completes the setup. Save both the project files and press F5 to launch the ASP.NET Core web app in the browser. You will find that correctly displays the HelloWorld component but the browser's address bar will now have URL of the ASP.NET Core web app.

We have used many special files in this two part series such as _Host.cshtml, App.razor, and _Imports.razor. I assumed that you are already familiar with these files. Just in case you aren't familiar with Blazor's project structure visit official documentation here

That's it for now! Keep coding!!


Bipin Joshi is an independent software consultant, trainer, author, yoga mentor, and meditation teacher. He has been programming, meditating, and teaching for 24+ years. He conducts instructor-led online training courses in ASP.NET family of technologies for individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

Get connected : Facebook  Twitter  LinkedIn  YouTube

Posted On : 31 May 2021


Tags : ASP.NET ASP.NET Core .NET Framework C# Visual Studio Components


Subscribe to our newsletter

Get monthly email updates about new articles, tutorials, code samples, and how-tos getting added to our knowledge base.

  

Receive Weekly Updates