2014-12-03 43 views
5

爲了記錄目的,我試圖監視通過WebAPI進行的請求。我已經創建好了,並且我正在尋找一種方法,在請求完成並做出迴應後,找回請求中發送的主體。我試圖通過使用ActionFilter來做到這一點,但是迄今爲止沒有從請求中讀取正文。取回請求ActionFilter中的主體

有沒有人可以提供一些建議,我可以如何獲得這些信息?

對於背景我想這個代碼中做到這一點:

public class LoggingActionFilter : ActionFilterAttribute 
    { 
     public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken) 
     { 
      var test = actionExecutedContext.Request.Content.ReadAsStringAsync().Result; 

      return base.OnActionExecutedAsync(actionExecutedContext, cancellationToken); 
     } 
    } 

我試圖以找回身體上actionExecutedContext變回讀Content卻發現這回只是空白等等遠。

回答

4

你只是處理請求主體,從而不需要使用OnActionExecutedAsync方法,你可以重寫OnActionExecuting這樣,

public override void OnActionExecuting(HttpActionContext actionContext) 

    { 
     var test = (actionContext.Request.Content as ObjectContent).Value.ToString(); 
     // your logging code here 
    } 

中的WebAPI提供另一種選擇是DelegatingHandler。如果你想記錄只是要求身體然後覆蓋SendAsync方法,

public class ApiLogHandler : DelegatingHandler 
{ 
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,   
               CancellationToken cancellationToken) 
{ 
    var requestBody = request.Content.ReadAsStringAsync().Result; 
    // your logging code here 
    return base.SendAsync(request, cancellationToken); 
} 
} 

如果您決定選擇DelegatingHandler,那麼你需要的是處理程序註冊Global message handlers

+1

我試過了OnActionExecuting命令,但沒有運氣,它會拋出一個'Object reference not set to object of instance' error。委託處理程序的想法確實有效,但我希望在請求完成後執行。這可能嗎? – 2014-12-03 13:42:46

+0

按照您的建議將我的功能更改爲使用非Async函數之後,我可以通過'actionExecutedContext.Request.Content.ReadAsStringAsync()。Result'返回正文。謝謝! – 2014-12-03 13:47:46