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.
- Visual Studio 2022. Version 17.12.0 or above. It will work with the free community version.
- .NET 9 SDK. Version 9.0.0 or above.
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.
Download this code example
Enter your email and we'll send you a download link.
Related code examples
Download & install this .NET code sample written in C# that uses a custom logging provider to log to a SQL Server database table
An ASP.NET Core for .NET 5 Web API which extends .NET Core's logging feature to log to text files in a HostedService.
Download this code example
Enter your email and we'll send you a download link.