在ASP.NET全局异常处理5 [英] Global exception handling in ASP.NET 5

查看:200
本文介绍了在ASP.NET全局异常处理5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何附上我自己的日志逻辑到ASP.NET 5应用程序来处理业务逻辑和下层抛出的每个异常?

How can I attach my own logging logic to an ASP.NET 5 application to handle each exception thrown in the business logic and lower layers?

ILoggerProvider 实施和Startup.cs loggerfactory.AddProvider(新LoggerProvider(配置))用自己的尝试。但似乎它拦截内ASP.NET的东西,而不是我抛出的异常的较低层。

I tried with own ILoggerProvider implementation and loggerfactory.AddProvider(new LoggerProvider(Configuration)) in Startup.cs. But it seems that it intercepts inner ASP.NET stuff, and not my thrown exceptions in lower layers.

推荐答案

的工作了,通过使用两个选项:

Worked it out, by using two options:

1)ILoggerProvider
实现从命名空间Microsoft.Framework.Logging自己ILoggerProvider和ILogger然后将其连接到MVC框架中添加Startup.cs以下code:

1) ILoggerProvider Implement your own ILoggerProvider and ILogger from the namespace Microsoft.Framework.Logging Then attach it to the MVC Framework in Startup.cs add following code:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory)
 {
        loggerfactory.AddProvider(new YourCustomProvider());
 }

但是,这上面的选项,似乎只能叫ILogger的写入功能MVC的具体事件,路由相关的等等,当我把我的下层例外,所以第二个选项摸索出它不叫:

But this above option, seems to only call the Write function of the ILogger on MVC specific events, routing related and so on, it wasn't called when I threw exceptions on my lower layers, so the second option worked out:

2)全局筛选
注册您自己ActionFilterAttribute实施Startup.cs:

2) Global Filter Register your own ActionFilterAttribute implementation in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new YourCustomFilter());
    });
}

这一点很重要,即自定义过滤器类实现了个IExceptionFilter interace:

It's important, that the custom filter class implements the IExceptionFilter interace:

  public class YourCustomFilter : ActionFilterAttribute, IExceptionFilter
  {
             public void OnException(ExceptionContext context)
             {
              ///logic...
             }
 }

()
然后在启动类中,我们添加过滤器:

() And then in the Startup class we add the filter:

    public void ConfigureServices(IServiceCollection services)
    {
         services.AddMvc(options =>
            {
                options.Filters.Add(new YourCustomFilter());
            });
    }

这篇关于在ASP.NET全局异常处理5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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