Web API ExceptionLogger [英] Web API ExceptionLogger

查看:47
本文介绍了Web API ExceptionLogger的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用IExceptionLogger和ExceptionHandler来为我的Web api服务全局记录和进行错误处理.

I am using IExceptionLogger and ExceptionHandler for logging and error handling globally for my web api service.

现在有什么方法可以从ExceptionLoggerContext上下文中读取POST数据.?只是因为我想保存POST数据以及异常详细信息.

Now Is there any way to read the POST data from ExceptionLoggerContext context. ? Just because i would like to save the POST data along with exception details.

推荐答案

我发现的唯一方法是解析 ExceptionLogger / IExceptionLogger 实现.

The only way I've found is to parse the ExceptionLoggerContext.ExceptionContext in your ExceptionLogger/IExceptionLogger implementation.

ExceptionLoggerContext.ExceptionContext 的类型为 System.Web.Http.ExceptionHandling.ExceptionContext .

您必须导航一些嵌套对象,但是到某个时候,您会发现:

There are a few nested objects you have to navigate, but at some point, you will find:

((System.Web.Http.ApiController)exceptionContext.ControllerContext.Controller).ActionContext.ActionArguments

包含一个 ValueCollection ,其中包含 FORM 的所有参数.

which contains a ValueCollection with all the arguments of your FORM.

在我的解决方案中,我实现了以下内容:

In my solution I've implemented something like this:

public class MyExceptionContext
    {
    public Dictionary<string, object>.ValueCollection ActionArguments { get; set; }

    public MyExceptionContext(System.Web.Http.ExceptionHandling.ExceptionContext exceptionContext)
    {
        try
        {
        this.ActionArguments = ((System.Web.Http.ApiController)exceptionContext.ControllerContext.Controller).ActionContext.ActionArguments.Values;
        }
        catch (Exception)
        {
        }
    }
}

我通过了我的构造函数 ExceptionLoggerContext.ExceptionContext ;它将使用发布的所有值填充字典 ActionArguments .

I pass my constructor ExceptionLoggerContext.ExceptionContext; it will populate the dictionary ActionArguments with all the values posted.

您可以在Github上找到演示项目.这是一个自托管的(owin)web.api应用程序.在我的启动中,我定义了我的自定义实现 IExceptionLogger IExceptionHandler .

You can find a demo project on Github. It's a self-hosted (owin) web.api application. In my Startup I've defined my custom implementation of IExceptionLogger and IExceptionHandler.

在此示例应用中,我使用了Serilog在磁盘上流式传输异常.

如果您尝试将表单发布到测试控制器,我将抛出异常,该异常将被全局处理程序捕获,并通过一些信息保留在文件系统上.

If you try to post a form to the test controller, I'll throw an exception which will be trapped by a global handler and persisted on the file system with some info.

如果下载并运行Github中的示例,则可以使用Fiddler对其进行测试:

If you download and run the example found in Github you can use Fiddler to test it:

POST http://localhost:9667/api/exception HTTP/1.1
User-Agent: Fiddler
Content-Type: application/x-www-form-urlencoded
Host: localhost:9667
Content-Length: 40

username=stackoverflow&password=password

这篇关于Web API ExceptionLogger的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆