【问题标题】:Get back Request Body within ActionFilter在 ActionFilter 中取回请求正文
【发布时间】:2015-01-31 11:29:04
【问题描述】:

出于日志记录的目的,我正在尝试监视通过 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 以取回正文,但发现到目前为止它只返回空白。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-web-api asp.net-web-api2


    【解决方案1】:

    您只是在处理请求正文,因此不需要使用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

    【讨论】:

    • 我已经尝试过 OnActionExecuting 命令,但没有成功,它会引发 Object reference not set to an instance of an object 错误。委托处理程序的想法确实有效,但我希望在请求得到满足后这样做。这可能吗?
    • 按照您的建议将我的函数更改为使用非异步函数后,我能够通过actionExecutedContext.Request.Content.ReadAsStringAsync().Result 取回我想要的主体。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多