我们正在使用Web API 2来处理异常,我们通过继承ExceptionFilterAttribute来创建自定义属性。现在我们要在异常的情况下将JSON请求的日志保存到数据库。
我尝试使用context.Request.Content.ReadAsStringAsync()读取。结果但返回空字符串。
请帮助!!
答案 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();
}
}
}