0
votes

In my ASP.NET core 3.1 web api, I'm using the ObjectResult StatusCode([ActionResultStatusCode] int statusCode, [ActionResultObjectValue] object value) method from ControllerBase to return certain types of errors with a 422 status code. In previous ASP.NET versions, throwing an exception with the status code information was standard and the logger would pick it up because it was an actual exception. Now I have code like this

public async Task<IActionResult> RequestSomething(RequestObject request)
{
  if(request.id == 0)
  {
    return StatusCode(422, "ID cannot be blank.");
  }
}

I was expecting to see something in app insights related to this, but there is nothing. Ideally I would have the message as well, but at least a log of the error would be a good start! I have requests, exceptions, dependency calls all showing up so I know it's hooked up and working.

I do not want to inject a logger everywhere and add a logging line before each of these. How do I setup Application Insights to capture all 422 status code results when returned this way?

1
From the documentation "Older versions of the SDK do not support ASP.NET Core 3.X.". Is your Application Insights version up to date?D A
yes, I'm using the latest version. thank you for the double check though!MPavlak
@MPavlak, can you use visual studio to debug it? and make sure this line is actually executed?Ivan Yang

1 Answers

0
votes

You are absolutely Correct. You don't need to inject the Logger in all the Controllers/ method. All you need to do the below.

  1. Install Nuget Package (Microsoft.ApplicationInsights.AspNetCore)
  2. Add services.AddApplicationInsightsTelemetry(); in your ConfigureServices method of Startup.
  3. Link the App Service and Application Insights (which I think you have already done).

Below is how it looks in the App Insights.

my Code in ActionMethod is something similar to yours.

[HttpGet]
        public IActionResult Get()
        {
                return StatusCode(422, "ID cannot be blank or 1.");
        }

enter image description here

For others who are new to App Insights, You can learn how to integrate App insights with App Service at https://praveenkumarsreeram.com/2020/07/11/6-steps-to-integrate-application-insights-with-net-core-application-hosted-in-azure-app-service/