Adding a .NET 6 minimal Web API to a Blazor Server project
By Martijn Storck
Back in .NET 6 Preview 4, minimal Web APIs were introduced into ASP.NET Core. Minimal Web APIs allow .NET developers to write small applications like microservices that server Web API endpoints with minimal code, making the experience similar to what one might see in Go or Ruby.
Since this functionality is part of the framework, it can easily be added to a Blazor Server application. This can be useful for things like health checks or metrics endpoints. Let’s build a new blazor server app and explore the possibilities.
dotnet new blazorserver -o Demo
Adding an endpoint
Open Program.cs
and find the section where the WebApplication
instance is created.
Insert the new endpoint definition right above the app.Run()
statement. Take
this simple HelloWorld example:
// ... existing Blazor initialization code ...
var app = builder.Build();
// ... existing Blazor initialization code ...
app.MapGet("/hello", () => "Hello, World!");
app.Run();
Run you app using dotnet run
and check the result from the terminal:
$ curl -i http://localhost:5000/hello
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Server: Kestrel
Hello, World!
Dependency Injection and JSON responses
Let’s improve functionality. Dependency Injection is available for these endpoints, so we can easily inject a service that we want to report the health of.
In the new minimal Program.cs you can add a class definition at the bottom. Append this simple, always healthy,
service class to your Program.cs
:
class MyService
{
public bool Healthy => true;
}
// End of file
Add this service to the DI container by adding this line to the builder section near the top of Program.cs
:
// ... existing services configuration ...
builder.Services.AddSingleton<MyService>();
Now, we are ready to inject MyService into our health check endpoint:
app.MapGet("/health", (MyService myService) => new { Healthy = myService.Healthy });
Notice how the anonymous object is automatically transformed into JSON:
$ curl -i http://localhost:5000/health
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Kestrel
{"healthy":true}
The new minimal APIs in .NET 6 make creating low-ceremony microservices and backends very appealing, and they’re also a great way to add simple endpoints to Blazor Server applications without having to pull in MVC components like Controllers and Routing.
In my P1Dash project I use this to export the smart meter readings as Prometheus metrics in addition to presenting them in the Blazor frontend, reusing the already available DSMR service. That code can be found on GitHub
Bedrijf foto gemaakt door freepik - nl.freepik.com