Blazor is a modern framework for building web applications with C#/.NET. Blazor apps can run "anywhere" in a variety of rendering modes. Blazor supports building pre-rendered static sites, server rendered web applications, and client-rendered web applications. With .NET 8, these rendering modes can be mixed and changed on a component-by-component basis.
This post focuses on using Blazor Server to render a web application. Blazor Server handles changes on the server then streams DOM updates to the browser via a SignalR connection.
ASP.NET Web API is a modern, but older and very mature, framework for building Web APIs with C#/.NET.
You can write a Blazor Server project to retrieve data without using ASP.NET WebAPI, this post will focus on adding a Blazor Server App to an existing Model/Controller WebAPI project.
We will first set up a sample Web API project with Controllers. Then we will set up a sample Blazor server application.
Then, we will merge the two together. Finally, we will write the code to invoke the Web API controller from the Blazor Server app.
First, let us set up a Web API project. With the dotnet cli, this is a one-line command in a terminal.
dotnet new webapi --name add_blazor_server -controllers
The --name
argument there, add_blazor_server
, can be whatever you want your project to be named. -controllers
specifies to use Controllers for your project rather than a newer "minimal API" project template.
In that screenshot we can see the contents of the root of the project. A few highlights:
Controllers
is the directory for our API Controllers.add_blazor_server.csproj
is the project file that specifies things like NuGet package dependencies and which version of .NET to use.add_Blazor_server.http
is a file that specifies a request with which you can test the api. This is a convenient tool for those of us used to more heavyweight tools such as Postman.appsettings.json
and appsettings.Development.json
are JSON configuration files for application settings. Some things are pre-defined in them.Program.cs
is the Entry Point of the project.WeatherForecase.cs
provides a sample Model object for us to work with.Now that we have our API Controllers, we can add a Blazor Server application.
In order to understand this, lets create a sample Blazor server project and look at a few things.
Just like the Web API project, we can create a blazor server project with the dotnet cli:
dotnet new blazorserver --name demo_blazorserver
Inside our demo blazor server project, we have some overlapping files with our WebApi and some new things. Here are a few highlights:
Data
provides some sample Data Access features for the blazor server app. Our objective will be to use the Blazor Server app with the API provided by ASP.NET Web Api instead of this.Pages
, Shared
, and wwwroot
are all for our Blazor Server razor pages UI experience. We'll keep these.Program.cs
is here as well and we will need to merge what happens in here with our Program.cs
in our Web API project.Adding Blazor to the ASP.NET Project
Now, let's add to the Web API project what we will need to run a blazor server and Web API Controller together in a single project.
First, we will add what we need in the Web API project's Program.cs
. In the Services setup, we need to invoke a few methods to register Blazor Services.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
Then, in that same file we set up middleware, we add Blazor pipelines middlewares. Add them after the MapControllers()
call so that our API controllers get "first dibs" at an incoming HTTP request.
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.UseStaticFiles();
app.UseRouting();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();
Then, we can copy some things. Copy App.razor
, _Imports.razor
, wwwroot
, Shared
, and Pages
.
Make sure the namespaces are aligned properly in the single project.
You'll get a few errors related to a missing Data
namespace. Remember, this is the sample data access code from our blazor server app. We're going to change this code to use our Web API controller instead.
After removing broken dependencies from the FetchData.razor
page, we have an app that runs, but the FetchData page doesn't do anything.
We can run the app with dotnet run
and give this a test.
But, we can get the data if we point our browser directly at the route for our API controller.
So, we have our app running both a Web API controller and a Blazor Server app. All that's left is updating some code in our Razor component, so the Blazor Server part of our app can call the Web API controller part of our app.
Let's make an API call in our FetchData.razor
call to replace the WeatherForecastService code we removed.
First, we set up a new Service in Program.cs
, the HTTP Client. This allows us to inject an HTTPClientFactory into our Razor component so we can make HTTP calls.
builder.Services.AddHttpClient();
Then, in FetchData.razor
, we inject two services, NavigationManager
and HttpClientFactory
. We will need the NavigationManager, a class provided by the Blazor framework, so the HTTPClient knows what URI to call.
While both the web api and the blazor server app are running in the same runtime here, this httpclient could make http calls out to whatever endpoints it has access to.
@inject IHttpClientFactory HttpClientFactory
@inject NavigationManager NavigationManager
Then we can update the OnInitializedAsync()
call of our FetchData
component.
protected override async Task OnInitializedAsync()
{
var httpClient = this.HttpClientFactory.CreateClient();
httpClient.BaseAddress = new Uri(NavigationManager.BaseUri);
forecasts = await httpClient.GetFromJsonAsync<WeatherForecast[]>("/weatherforecast");
}
Then we ran run our app one more time with dotnet run
and see that the 'Fetch Data' page is pulling data from our Web API Controller.
This article provides a step-by-step guide to combining Blazor Server with an ASP.NET Web API, ensuring seamless data integration and a functional web application.
We first made a sample Web API project, and a sample Blazor Server project. We accomplished this with a few commands from the dotnet cli, a tool that the author is particularly fond of.
After that, we walked through migrating the Blazor server functionality into the Web API project.
Once that was running, we programmed a Blazor server razor component to make HTTP calls to our Web API controller in the same project.
We included a few screenshots of the app along the way. If you would like to see all the code together, you can check it out at GitHub here: https://github.com/dsschnau/add_blazor_server_app_to_aspnet_web_api. Great job, thanks for reading!