如果异常,如何在HttpActionExecutedContext中读取JSON主体

时间:2016-08-09 11:16:58

标签: asp.net-web-api2 httpcontext

我们正在使用Web API 2来处理异常,我们通过继承ExceptionFilterAttribute来创建自定义属性。现在我们要在异常的情况下将JSON请求的日志保存到数据库。

我尝试使用context.Request.Content.ReadAsStringAsync()读取。结果但返回空字符串。

请帮助!!

1 个答案:

答案 0 :(得分:1)

您可以重置请求流位置并重新读取它:

class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override async Task OnExceptionAsync(HttpActionExecutedContext context, CancellationToken cancellationToken)
    {
        var stream = await context.Request.Content.ReadAsStreamAsync();
        stream.Position = 0;
        using (var reader = new StreamReader(stream))
        {
            var requestString = reader.ReadToEnd();
        }
    }
}