如何记录Web服务的JSON请求

sve*_*vit 5 c# asp.net jquery trace json

我有一个web方法,从jquery的ajax方法调用,如下所示:

$.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");
    }
});
Run Code Online (Sandbox Code Playgroud)

这是我的网络方法:

[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());
    }
}
Run Code Online (Sandbox Code Playgroud)

如果javascript中的myClass被序列化为正确的格式,则DoSomething方法执行并将原始json保存到数据库.但是如果myClass出错了,那么该方法根本不会执行,我无法记录有问题的json ......

即使序列化失败,总是以某种方式获取并记录我的Web方法接收的原始json的最佳方法是什么?

sve*_*vit 1

在 stackoverflow 上的一些其他答案的帮助下,我得出了以下结论:

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
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

在 web.config 中:

<httpModules>
  <add name="MyRequestLogModule" type="MyNamespace.RequestLogModule, MyAssembly"/>
</httpModules>
Run Code Online (Sandbox Code Playgroud)