簡體   English   中英

如何記錄Web服務的JSON請求

[英]How to log JSON requests of web services

我有一個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的最佳方法是什么?

在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>

你總是可以在服務器端做到這一點。

當您將請求發送到調用Web服務的“MyWebService.aspx / DoSomething”時,您可以將結果(成功/錯誤)記錄到日志文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM