在操作过滤器中取回请求正文
本文关键字:请求 正文 操作 过滤器 | 更新日期: 2023-09-27 18:32:50
出于日志记录目的,我正在尝试监视通过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);
}
}
我尝试回读 actionExecutedContext
变量上的Content
以取回正文,但到目前为止发现它只是空白。
你只是在处理请求体,所以不需要使用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
。