Note: I'm new to c# and .net
I'm working on recording logs and metrics for APIs and specific operations. To achieve this, I'm planning to use middleware. I've implemented a basic version of middleware along with a custom attribute, and that works fine*** with API methods like 'PostUsers' in the below example code snippet.
namespace MyApp.Namespace1
{
[ApiController]
public class Controller : ControllerBase
{
[HttpPost]
[Route( "users" )]
[OperationName( "PostUsers" )] // Custom attribute to send the operation name to middleware
public async Task PostUsers( [FromBody] UsersRequest request )
{
try
{
...
}
catch ( Exception ex )
{
...
// This error (ex.Message, etc.) should be available in middleware
}
}
}
}
But when I apply the attribute and middleware to the non-controller methods like 'HandleUsers' and 'CreateStorage,' mentioned in the code snippet below, it doesn't work
internal class UsersProvider
{
[OperationName( "HandleUsers" )]
private async Task HandleUsers()
{
}
}
public class Storage
{
[OperationName( "CreateStorage" )]
private static void CreateStorage( )
{
}
}
Is there any way to achieve a similar pattern so that it can be applied to all types of methods?
***: Currently, I'm passing the required details from the controller to the middleware by using HttpContext.Items. Is there any better way of doing this? My goal is to offload all the logs and metric-related logic to middleware and keep the controller/target method as clean as possible