Reputation: 2221
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?
Upvotes: 0
Views: 487
Reputation: 1278
You are absolutely Correct. You don't need to inject the Logger in all the Controllers/ method. All you need to do the below.
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.");
}
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/
Upvotes: 0