出于日志记录的目的,我正在尝试监视通过WebAPI发出的请求。我已创建并且我正在寻找一种方法,在请求完成并回复后,在请求中返回已发送的正文。我试图通过使用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);
}
}
我已经尝试回读Content
变量上的actionExecutedContext
以便取回身体,但发现这只是为了返回空白。
答案 0 :(得分:6)
您只是处理请求正文,因此不需要使用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
。