How to log web service JSON requests

I have a web method that is being called from jQuery ajax, for example:

$.ajax({
    type: "POST",
    url: "MyWebService.aspx/DoSomething",
    data: '{"myClass": ' + JSON.stringify(myClass) + '}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: false,
    success: function (result) {
        alert("success");
    },
    error: function () {
        alert("error");
    }
});

And this is my web method:

[WebMethod(EnableSession = true)]
public static object DoSomething(MyClass myClass)
{
    HttpContext.Current.Request.InputStream.Position = 0; 
    using (var reader = new StreamReader(HttpContext.Current.Request.InputStream))
    {
    Logger.Log(reader.ReadToEnd());
    }
}

If myClass in javascript is serialized to fix the format, the DoSomething methods are executed and retain the original json for the database. But if myClass is wrong, the method fails at all, and I cannot register the problematic json ...

What is the best way to always get and write the raw json that my web method gets, even if serialization fails?

+5
source share
2 answers

With some other answers on stackoverflow, I came to the following:

public class RequestLogModule : IHttpModule
{
    private HttpApplication _application;

    public void Dispose()
    {
    }

    public void Init(HttpApplication context)
    {
        _application = context;
        _application.BeginRequest += ContextBeginRequest;
    }

    private void ContextBeginRequest(object sender, EventArgs e)
    {
        var request = _application.Request;

        var bytes = new byte[request.InputStream.Length];
        request.InputStream.Read(bytes, 0, bytes.Length);
        request.InputStream.Position = 0;
        string content = Encoding.UTF8.GetString(bytes);

        Logger.LogRequest(
            request.UrlReferrer == null ? "" : request.UrlReferrer.AbsoluteUri,
            request.Url.AbsoluteUri,
            request.UserAgent,
            request.UserHostAddress,
            request.UserHostName,
            request.UserLanguages == null ? "" : request.UserLanguages.Aggregate((a, b) => a + "," + b),
            request.ContentType,
            request.HttpMethod,
            content
        );
    }
}

And in the web.config file:

<httpModules>
  <add name="MyRequestLogModule" type="MyNamespace.RequestLogModule, MyAssembly"/>
</httpModules>
+1
source

You can always do this on the server side.

"MyWebService.aspx/DoSomething", -, (/) .

-3

All Articles