Unity异常拦截-配置

Unity exception interception - configuration

我希望在 MVC 或 Web API 层有一组拦截器来捕获任何异常,获取生成异常的 URI,并从配置中查找返回给用户的消息。

例如 POST 到 /api/v1/user 引发唯一约束违规将被配置为响应 "User already exists",而 POST [=19= 的相同异常] 会回应 "VIN is already in system".

Unity 中有这方面的工具吗?如果没有,有人有来自公开来源的示例吗?

Unity 不是在 ASP.NET 应用程序中自定义错误响应的合适工具。它是一个依赖注入容器,您希望它只用所有必需的依赖项实例化您的控制器。将它与应用程序逻辑混合是个坏主意(自定义错误响应当然是其中的一部分)。

ASP.NET MVC 和 ASP.NET Web API 提供了一个完全适合您需要的扩展点 - 异常过滤器。这是 ASP.NET Web API:

的示例
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        //  Add  your exception handling here

        //  Check context.Exception and decide whether you need to handle it
        if (context.Exception is SqlException)
        {
            var controllerType = context.ActionContext.ControllerContext.Controller.GetType();

            if (controllerType == typeof(UserController))
            {
                context.Response = new HttpResponseMessage(HttpStatusCode.Conflict)
                {
                    Content = new StringContent("User already exists")
                };
            }
            else
            {
                // Cover other controller types here
            }
        }
    }
}

如您所见,实施非常简单。在 OnException() 方法中,您可以使用控制器和操作上下文访问异常本身。 如果您的逻辑需要为此控制器操作处理此异常,您只需用适当的 HttpResponseMessage 填充 context.Response,选择 HTTP 状态代码和正文。

您可以使用

全局应用此类异常过滤器
GlobalConfiguration.Configuration.Filters.Add(new CustomExceptionFilterAttribute());

在您的 WebApiConfig.Register(HttpConfiguration config) 或控制器级别:

[CustomExceptionFilter]
public class UserController : ApiController

ASP.NET MVC 的实现非常相似。在那种情况下,您的过滤器应该实现 System.Web.Mvc.IExceptionFilter.