2014-12-03 39 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