5

I have a web method, which is called from jquery's ajax method, like this:

$.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 correct format, then DoSomething methods executes and saves the raw json to database. But if myClass is in wrong then the method doesn't execute at all and I can't log the problematic json...

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

4

2 に答える 2

1

With the help of some other answers on stackoverflow I came to this:

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:

<httpModules>
  <add name="MyRequestLogModule" type="MyNamespace.RequestLogModule, MyAssembly"/>
</httpModules>
于 2012-05-16T10:57:38.613 に答える
-3

あなたはいつでもサーバー側でそれを行うことができます。

Webサービスを呼び出す「MyWebService.aspx/DoSomething」にリクエストを送信すると、結果(成功/エラー)をログファイルに記録できます。

于 2012-05-15T11:09:11.687 に答える