在 Web api IExceptionHandler 中获取请求正文

Dav*_*ans 5 asp.net asp.net-web-api owin asp.net-web-api2

我正在尝试为 ASP.NET web api 编写一个全局错误处理程序,它能够记录在我的 api 中导致未处理异常的请求的请求详细信息。我已经在我的 OWIN 启动类中注册了以下 GlobalExceptionHandler 类,但我无法检索请求正文中发布的任何数据的内容。

public class GlobalExecptionHander : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        var body = context.Request.Content.ReadAsStringAsync().Result;
        //body here is an empty string

        context.Result = new UnhandledErrorActionResult
        {
            Request = context.Request,
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的创业班

config.Services.Replace(typeof(IExceptionHandler), new GlobalExecptionHander());
Run Code Online (Sandbox Code Playgroud)

Bak*_*een 4

由于我刚刚遇到这个问题,我很惊讶地发现这个问题没有答案!我希望经过这么长时间你已经解决了这个问题。不管怎样我还是想回答这个问题。

问题是,当您GlobalExceptionHandler处理异常时,某些东西(例如 Newtonsoft Json 或任何其他请求处理程序)已经读取了 HTTP 请求的内容流。读取流后,您无法再次读取它,除非有某种方法将该流重置到其初始位置......

public override void Handle(ExceptionHandlerContext context)
{
    string requestContent = "";
    using(System.IO.Stream stream = context.Request.Content.ReadAsStreamAsync().Result)
    {
        // Set the stream back to position 0...
        if (stream.CanSeek)
        {
            stream.Position = 0;
        }

        // ... and read the content once again!
        requestContent = context.Request.Content.ReadAsStringAsync().Result;
    }

    /* ..Rest of code handling the Exception.. */
}
Run Code Online (Sandbox Code Playgroud)

原因requestContent是在该using块之外,因为流在​​块关闭后被释放。您也可以在阅读完内容后退出using并致电。stream.Dispose()