我的ASPNETCore API中有一个ExceptionFilterAttribute,我处理某些异常类型。
例如任何UnauthorizedAccessException我返回HttpStatusCode.Unauthorized,任何KeyNotFoundException我返回HttpStatusCode.NotFound等。
但是,我还会返回一条基本信息。例如,字符串" Key Not Found"与HttpStatusCode.NotFound一起返回。
我希望使用IStringLocalizer解析ExceptionFilterAttribute中包含的消息。但是,ExceptionFilterAttribute似乎不支持依赖注入。
有没有人遇到同样的问题?
这里有一种被认为是最佳做法的方法吗?
答案 0 :(得分:0)
您可以从IServiceProvider
访问ExceptionContext
。
public override void OnException(ExceptionContext context)
{
var service = context.HttpContext.RequestServices.GetService<MyService>();
}