2
votes

I created webApi global exception handler, i have to log the request parameters/JSON in the prod environment to verify the request if any exception happened, Please let me know the way to log the request message with in the

ExceptionHandler
.

WebApiConfig

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Services.Replace(typeof (IExceptionHandler), 
            new GlobalExceptionHandler());
    }
}

GlobalExceptionHandler

public class GlobalExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
     Logger.log("Exception : \t" + context.Exception.Message)
         Logger.log("Request JSON : \t" + Josn.Serializer(context.Request.Content));
    }
}
1
So what's the problem with the above code?Jayakrishnan
Not able to get the Request JSON from body of the WebAPI request, here i am not able get that requestGopinath2105
Have you check the context.RequestContext ?Marcus Höglund

1 Answers

2
votes

You can try reading the content like following.

For POST/PUT/DELETE following code will read the content.

     string jsonContent = "";
     System.Web.HttpContext.Current.Request.InputStream.Position = 0;
     using (var reader = new StreamReader(System.Web.HttpContext.Current.Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
         {    
          jsonContent= reader.ReadToEnd().ToString();
         }

 //Reset back the position
     System.Web.HttpContext.Current.Request.InputStream.Position = 0;

For GET request you can log the URL directly.