Search code examples
c#jsonweb-services.net-3.5webmethod

Access raw JSON from inside asp.net WebMethod


I have a System.Web.Services.WebService containing several WebMethods. If any of these WebMethods raises an exception, I want to log the values passed to that WebMethod. I want to handle this in a way that is generic enough that I can use the same method regardless of the number or type of parameters. I thought I would log the raw JSON but I am unable to determine how to access it. I have searched throughout the Context.Request object (including the InputStream property) without finding it.

Here is what I would like to do:

[WebMethod(EnableSession = true)]
public IEnumerable MyWebMethod(int a, string b)
{
    try
    {
      //do something
    }
    catch (Exception e)
    {
      LogException(e, this.Context);
      throw;
    }
}

//All WebMethods should be able to call LogExceoption regardless of param type/count
protected void LogException(Exception ex, HttpContext context)
{
  string parameters = context.Request. //?? i don't know how to get to the JSON
  //write exception detail to log
}

I am using C# with .net Framework 3.5


Solution

  • Here is how to access the raw JSON:

    protected void LogException(Exception ex, HttpContext context)
    {
        context.Request.InputStream.Position = 0;
        string rawJson = null;
        using (StreamReader reader = new StreamReader(context.Request.InputStream))
        {
            rawJson = reader.ReadToEnd();
        }
        //write exception detail to log
    }