C# 如何在异常处理程序WebAPI中获取请求JSON消息? ExceptionHandler

C# 如何在异常处理程序WebAPI中获取请求JSON消息? ExceptionHandler,c#,.net,asp.net-web-api,C#,.net,Asp.net Web Api,我创建了webApi全局异常处理程序,我必须在prod环境中记录请求参数/JSON以验证请求。如果发生任何异常,请告诉我如何在ExceptionHandler中记录请求消息 ExceptionHandler WebApiConfig 公共静态类WebApiConfig { 公共静态无效寄存器(HttpConfiguration配置) { config.Services.Replace(typeof(IEExceptionHandler), 新的GlobalExceptionHandler());

我创建了webApi全局异常处理程序,我必须在prod环境中记录请求参数/JSON以验证请求。如果发生任何异常,请告诉我如何在ExceptionHandler中记录请求消息

ExceptionHandler WebApiConfig

公共静态类WebApiConfig { 公共静态无效寄存器(HttpConfiguration配置) { config.Services.Replace(typeof(IEExceptionHandler), 新的GlobalExceptionHandler()); } } GlobalExceptionHandler

公共类GlobalExceptionHandler:ExceptionHandler { 公共重写无效句柄(例外HandlerContext上下文) { Logger.log(“异常:\t”+上下文.Exception.Message) log(“请求JSON:\t”+Josn.Serializer(context.Request.Content)); }
} 您可以尝试阅读以下内容

对于
POST/PUT/DELETE
,以下代码将读取内容

     string jsonContent = "";
     System.Web.HttpContext.Current.Request.InputStream.Position = 0;
     using (var reader = new StreamReader(System.Web.HttpContext.Current.Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
         {    
          jsonContent= reader.ReadToEnd().ToString();
         }

 //Reset back the position
     System.Web.HttpContext.Current.Request.InputStream.Position = 0;

对于
GET
请求,您可以直接记录
URL

那么上面的代码有什么问题?无法从WebAPI请求主体获取请求JSON,这里我无法获取该请求。您是否检查了上下文。RequestContext?无法访问ExceptionHandler中的httpContext。。让我知道如何访问我已经更新了答案,你应该可以像System.Web.HttpContext.Current.Request.InputStream一样获得它。你得到了内容吗?谢谢,我可以访问HttpContext,但是reader.TeadToEnd().ToString()是空字符串,即使内容长度是27。在我移动System.Web.HttpContext.Current.Request.InputStream.Position=0后,请让我知道我做错了什么;代码的开头。
     string jsonContent = "";
     System.Web.HttpContext.Current.Request.InputStream.Position = 0;
     using (var reader = new StreamReader(System.Web.HttpContext.Current.Request.InputStream, System.Text.Encoding.UTF8, true, 4096, true))
         {    
          jsonContent= reader.ReadToEnd().ToString();
         }

 //Reset back the position
     System.Web.HttpContext.Current.Request.InputStream.Position = 0;