【问题标题】:How to log JSON requests of web services如何记录 Web 服务的 JSON 请求
【发布时间】:2012-05-15 10:53:42
【问题描述】:

我有一个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");
    }
});

这是我的网络方法:

[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());
    }
}

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

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

【问题讨论】:

  • 尝试谷歌搜索“IIS日志请求httpmodule”你应该会发现一些有用的东西(抱歉我现在找不到相关代码)
  • @alex - 谢谢,IHttpModule 正是我所需要的。

标签: c# jquery asp.net json trace


【解决方案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
        );
    }
}

在 web.config 中:

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

【讨论】:

    【解决方案2】:

    你总是可以在服务器端做到这一点。

    当您将请求发送到调用 Web 服务的“MyWebService.aspx/DoSomething”时,您可以将结果(成功/错误)记录到日志文件中。

    【讨论】:

      猜你喜欢
      • 2013-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-11
      • 2012-01-07
      • 2018-03-03
      相关资源
      最近更新 更多