我正在测试 MVC 6 Web Api,并希望实现登录到全局错误处理程序。只是保证没有错误会在没有被记录的情况下离开系统。我创建了一个 ExceptionFilterAttribute 并将其全局添加到启动中:
public class AppExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
//Notice pulling from HttpContext Application Svcs -- don't like that
var loggerFactory = (ILoggerFactory)context.HttpContext.ApplicationServices.GetService(typeof (ILoggerFactory));
var logger = loggerFactory.Create("MyWeb.Web.Api");
logger.WriteError(2, "Error Occurred", context.Exception);
context.Result = new JsonResult(
new
{
context.Exception.Message,
context.Exception.StackTrace
});
}
}
现在在启动中,我将这个过滤器添加到:
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new AppExceptionFilterAttribute());
});
这一切看起来有点蛮力...有没有更好的方法使用 MVC 6 到达这里?
我不喜欢或不确定这种方法的事情:
- 不喜欢从 http 上下文中提取 DI
- 关于引发错误的控制器没有太多上下文(也许我可以通过某种方式从上下文中获取它)。
我能想到的另一个选择是有一个基本控制器,它接受所有控制器继承的 ILoggerFactory。
想知道是否有某种诊断中间件可以允许插入日志记录......
你的问题有两部分。 1) DI 可注入过滤器 2) 全局错误处理。
关于#1:你可以使用ServiceFilterAttribute
以此目的。
例子:
//Modify your filter to be like this to get the logger factory DI injectable.
public class AppExceptionFilterAttribute : ExceptionFilterAttribute
{
private readonly ILogger _logger;
public AppExceptionFilterAttribute(ILoggerFactory loggerfactory)
{
_logger = loggerFactory.CreateLogger<AppExceptionFilterAttribute>();
}
public override void OnException(ExceptionContext context)
{
//...
}
}
//Register your filter as a service (Note this filter need not be an attribute as such)
services.AddTransient<AppExceptionFilterAttribute>();
//On the controller/action where you want to apply this filter,
//decorate them like
[ServiceFilter(typeof(AppExceptionFilterAttribute))]
public class HomeController : Controller
{
....
}
您应该能够从以下位置获取控制器的详细信息ExceptionContext
那已经过去了。
关于#2:从你之前的帖子看来你正在玩ExceptionHandlerMiddleware
(source & 扩展源)...使用它怎么样?...有关它的一些信息:
- 该中间件是通用的,适用于任何中间件
是在它之后注册的,因此任何像控制器/操作这样的概念
info 是特定于 MVC 的,中间件不会意识到这一点。
- 该中间件不处理格式化程序写入异常。你可以
编写自己的缓冲中间件,您可以在其中修改响应
body 是一个缓冲流(MemoryStream)并让 MVC 层
写下对此的回应。在格式化程序写入异常的情况下,
您可以捕获它并发送包含详细信息的 500 错误响应。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)