...

/

Implementing Advanced Features for Web Services

Implementing Advanced Features for Web Services

Learn about implementing a health check API, Open API, transient fault handling, and adding security HTTP headers.

Implementing a Health Check API

Many paid services perform site availability tests that are basic pings, some with more advanced analysis of the HTTP response. ASP.NET Core 2.2 and later make it easy to implement more detailed website health checks. For example, the website might be live, but is it ready? Can it retrieve data from its database?

Let’s add basic health check capabilities to our web service:

Step 1: In the Northwind.WebApi project, add package references to enable Entity Framework Core database health checks, as shown in the following markup:

Press + to interact
<PackageReference Include="AspNetCore.HealthChecks.SqlServer"
Version="6.0.2" />
<PackageReference Include=
"Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore"
Version="7.0.0" />

Warning: AspNetCore.HealthChecks.SqlServer is not officially supported by Microsoft.

Step 2: Build the Northwind.WebApi project.

Step 3: In Program.cs, before the call to the Build method, add a statement to add health checks, including to the Northwind database context, and if you are using SQL Server instead of SQLite, as shown in the following code:

Press + to interact
builder.Services.AddHealthChecks()
.AddDbContextCheck<NorthwindContext>()
// execute SELECT 1 using the specified connection string
.AddSqlServer("Data Source=.;Initial Catalog=Northwind;Integrated Security=true;");

By default, the database context check calls EF Core's IDatabaseCreator.CanConnectAsync method. We can customize the method that is run by setting its name as a parameter in the AddDbContextCheck method.

Step 4: In Program.cs, before the call to MapControllers, add a statement to use basic health checks, as shown in the following code:

Press + to interact
app.UseHealthChecks(path: "/howdoyoufeel");

Step 5: Start the Northwind.WebApi web service project.

Step 6: ...