2

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));
    }
}
3
  • 1
    So what's the problem with the above code? Commented Feb 21, 2018 at 5:09
  • Not able to get the Request JSON from body of the WebAPI request, here i am not able get that request Commented Feb 21, 2018 at 5:32
  • Have you check the context.RequestContext ? Commented Feb 21, 2018 at 7:02

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

not able to access httpContext with in the ExceptionHandler.. Let me know how to access
I have updated the answer, you should be able to get it like System.Web.HttpContext.Current.Request.InputStream
Did you got the content?
Thanks i am able to access the HttpContext, but reader.TeadToEnd().ToString() is retruns empty string even though content length is 27. Please let me know what i did wrong
it workd after I moved System.Web.HttpContext.Current.Request.InputStream.Position = 0; beginning of the code.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.