Years ago, I wrote an article on how to configure Elmah to be used on Winhost. You may have noticed that there is no official support for ASP.NET Core, however, you can use ElmahCore by barestan to perform the same logging to a database, and this blog provides an example on how to set that up.
First, we’ll start by creating a New Project in Visual Studio:
- Go to File -> New Project… (Ctrl-Shift-N).
- Select Visual C# -> Web -> ASP.NET Core Web Application.
- Give the project/solution a name and click on OK.
- Select .NET Core in the left drop-down menu and ASP.NET Core 2.1 in the right drop-down menu. You can also just use the Empty project template.
- Click on OK.
- Now from the main menu up top, select Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution…
- Click on Browse in the NuGet – Solution window and type in ElmahCore.
- Highlight ElmahCore, check the box next to your project, and click on the Install button. Accept any license agreements and complete the installation.
- Now double click the Startup.cs file in the Solution Explorer window to open it.
- Add a using ElmahCore; directive at the top.
- In the ConfigureServices method, add the following code replacing connection_string with your actual Winhost database connection string. Make sure you’ve created the database and installed the Elmah tables as outlined in my instructions from my previous blog.
services.AddElmah<SqlErrorLog>(options => { options.ConnectionString = @"connection_string"; });
- In the Configure method, add the following code:
app.UseElmah();
That’s it. If you want to know if it’s working, you can generate a sample exception like this:
app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); int[] numbers = new int[5]; await context.Response.WriteAsync(numbers[6].ToString()); });
That will generate an “Index was outside the bounds of the array.” exception which will be logged into the database. You can query the dbo.ELMAH_Error table to see the results.
Visit Winhost to learn more about our .NET Core hosting solutions