簡體   English   中英

是否可以在將請求(JSON)轉換為模型綁定程序中的對象以及響應時進行記錄?

[英]Is it possible to log when the request (JSON) is transformed to object in model binder and also the response?

我想知道當將請求(以JSON格式)轉換為對象並且將對象作為響應(在模型綁定中)轉換為json時,是否可以實現日志記錄? 如果可能的話,我想避免在控制器中實現日志記錄,以獲取更簡潔的代碼。

編輯:

我需要記錄整個傳入和傳出的json字符串。

我也正在使用ASP.NET Web API 2。

當然,只要覆蓋默認的模型綁定器即可。

public class LoggingDataBinder : DefaultModelBinder
{

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
         var request = context.HttpContext.Request;
         //if you only want to deal with json requests
         if (request.ContentType == "application/json")
         {
              //can now access QueryString, URL, or InputStream
              using (var sr = new StreamReader(request.InputStream))
              {
                 var jsonData = sr.ReadToEnd();
                 LogMethod(jsonData);
              }    
         }
         return base.BindModel(controllerContext, bindingContext);
    }

} 

然后在Global.asax.cs.Application_Start()

protected void Application_Start(Object sender, EventArgs e)
{
     ModelBinders.Binders.DefaultBinder = new LoggingModelBinder();
}

您可以通過多種方式對此進行自定義(僅對特定類型,特定請求具有此自定義綁定器,從請求中獲取詳細信息以進行日志記錄),但這將滿足您有關發生模型綁定時如何進行記錄的問題。

編輯

為了處理日志記錄響應,我建議在您的控制器(或基本控制器)中重寫OnResultExecuted ,如下所示:

protected override void OnResultExecuting(ResultExecutingContext filterContext)
{
    //assuming this will be the type of all of your JSON data actions
    var json = filterContext.Result as JsonResult;
    if (json != null)
    {
         //assuming you haven't overriden the default serializer here,
         //otherwise may be inconsistent with what the client sees
         LogMethod(new JavaScriptSerializer().Serialize(json.Data));
    }
}

您可以創建自己的ActionFilterAttribute並適當地修飾控制器/動作方法(例如,僅修飾返回JsonResult動作方法),而不是在此級別上進行操作。 這是MSDN上的一篇老文章 ,仍然可以使您走上正確的道路。

編輯2我對Web API經驗不足,但是我認為最好的選擇是實現消息處理程序:

public class JsonMessageLoggerHandler : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        bool isJson = false;
        //not tested, you may have to play with this
        if (request.Content != null && request.Content.Headers.ContentType.MediaType == "application/json")
        {
            isJson = true;
            var requestText = await request.Content.ReadAsStringAsync();
            LogMethod(requestText);
        }
        // Call the inner handler.
        var response = await base.SendAsync(request, cancellationToken);

        //log the response
        if (isJson)
        {
            var responseText = await response.Content.ReadAsStringAsync();
            LogMethod(responseText);
        }

        return response;
    }
}

然后使用WebApiConfig類連接消息處理程序:

config.MessageHandlers.Add(new APITraceLogger());

同樣,我對Web API並不熟悉,因此您可能需要嘗試一下(坦率地說,這可能不是解決此問題的最佳方法)。 以下是一些鏈接,以獲取更多詳細信息: SO QuestionASP.NET

暫無
暫無

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

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