Request logging in ASP.NET Core example to save logs to a DB

You can add request logging to your ASP.NET Core Web API when you download this code example. It will get each HTTP request and save it to the database using Entity Framework Core and SQL Server.

Find out how we added request logging to an ASP.NET Core Web API, or watch the video:

Download the code example

You'll need to fill out the code example form. We will send you an email where you can download the code example.

The code example will be in a zip file.

Software

This is the software that will need to be installed onto your machine.

Import the database

Before you can run the application, you need to import the database into SQL Server. First of all, you need to make sure that both SQL Server and SQL Server Management Studio are installed on your machine.

Once you've done that, open up the zip file and go into the Database folder. You can either use the .bak or .bacpac file to import the database into SQL Server. We recommend giving it a name of RequestLogging.

Modify the connection string

The connection string is set in appsettings.Development.json file in the Api project. It's set up to use Local DB, have RequestLogging as the database name and use integrated security. You'll need to modify the connection string if any of these do not match.

Run the application

Open up RoundTheCode.RequestLogging.sln in Visual Studio and run the application. It should load up the Scalar documentation at https://localhost:5802/scalar/v1. Run the API test endpoint by calling https://localhost:5802/api/Test.

Now open up your database and the RequestLogging table. You should see the requests for the Scalar documentation and the API test endpoint have been added to the table. It should include the date in UTC, the HTTP method, the request path, IP address, user agent, response code and how long it took for the request to complete.