【问题标题】:Get request body in web api IExceptionHandler在 Web api IExceptionHandler 中获取请求正文
【发布时间】:2016-01-30 10:55:49
【问题描述】:

我正在尝试为 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,
        };
    }
}

在我的创业课上

config.Services.Replace(typeof(IExceptionHandler), new GlobalExecptionHander());

【问题讨论】:

    标签: asp.net asp.net-web-api asp.net-web-api2 owin


    【解决方案1】:

    由于我刚刚遇到这个确切的问题,我很惊讶地发现这个问题没有答案!我希望你在这段时间之后设法解决了这个问题。无论如何,我仍然想回答这个问题。

    问题是,当您的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.. */
    }
    

    requestContent 位于 using 块之外的原因是因为流在块关闭后被释放。你也可以去掉using,在阅读完内容后调用stream.Dispose()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-30
      • 2017-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      相关资源
      最近更新 更多