0

In my web api whenever any exception occurs i need to log the exception details into the database, along with the exception message and stack trace i need to store ClientId (The client application Id) and ClientUserId(The client user id) which will be available in all the action methods inside my web api.

Whenever any exception occurs the OnException method in my CustomExceptionFilter class automatically gets called, how do i pass the "ClientId", "ClientUserId" to this method when any exception occurs ?

    public class CustomExceptionFilter: ExceptionFilterAttribute  
    {  
        public override void OnException(HttpActionExecutedContext actionExecutedContext)  
        {  
            if(actionExecutedContext.Exception != null)
            {
               ExceptionLogger.LogException("ClientId", "ClientUserId",actionExecutedContext.Exception.Message, actionExecutedContext.Exception.StackTrace);
            }
        }
    }

Registered the filter in webapi config class

    public static class WebApiConfig  
    {  
      public static void Register(HttpConfigurationconfig)  
      {  
        config.Filters.Add(new CustomExceptionFilter());  
      }  
    }    
 
3
  • What are you using as Logger? MS default logger? I suggest you look into Serilog, or NLog as they provide better structured logging. Apparently after .netcore 3+, you can use structured logging in MSLogging something along the lines of this: Logger.LogException("Error: {message} \n ClientId: {ClientId}; ClientUserId: {ClientUserId}", actionExecutedContext.Exception.Message, ClientId, ClientUserId); The parameters are saved in the log message in a structured way. Did not try it in MSLogging myself though Commented Jun 2, 2021 at 18:01
  • I have updated my post and renamed Logger to ExceptionLogger to avoid confusion, ExceptionLogger is a plain c# class , I am using .NET 4.7 Commented Jun 2, 2021 at 18:06
  • Ah Ok. Take a look at this: stackoverflow.com/questions/39663296/… Commented Jun 2, 2021 at 18:32

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.