Jon*_*007 7 c# asp.net-mvc asp.net-web-api asp.net-web-api2
出于日志记录的目的,我试图监视通过WebAPI发出的请求.我已创建并且我正在寻找一种方法,在请求完成并回复后,在请求中返回已发送的正文.我试图通过使用a来做到这一点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);
}
}
Run Code Online (Sandbox Code Playgroud)
我曾尝试读回Content的actionExecutedContext,以取回体变量,但发现这回只是空白为止.
你只是处理请求体,所以不需要使用OnActionExecutedAsync方法,你可以OnActionExecuting像这样覆盖,
public override void OnActionExecuting(HttpActionContext actionContext)
{
var test = (actionContext.Request.Content as ObjectContent).Value.ToString();
// your logging code here
}
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您决定选择DelegatingHandler那么您需要注册该处理程序Global message handlers.
| 归档时间: |
|
| 查看次数: |
8661 次 |
| 最近记录: |