c# - 我怎样才能直接从我的特定于应用程序的异常映射到 Http 异常?

标签 c# asp.net-mvc action-filter custom-error-pages handleerror

我正在开发 ASP.NET MVC 3 应用程序。在我们应用程序的所谓“业务层”中,我们决定根据情况始终抛出一些特定类型的异常。我们有一个异常类型层次结构,当用户试图做一些他未经授权的事情时,以及当应用程序找不到给定项目(通过 ID 或名称或其他)时的特殊异常。

这在我们的 C# 代码中看起来像这样:

// ... more stuff
public Something GetSomething(int id, User currentUser){
    var theSomething = SomethingRepository.Get(id);
    if(theSomething == null){
        throw new SomethingNotFoundException(id, "more details");
    }

    if(!PermissionService.CanLoadSomething(currentUser)){
        throw new NotAuthorizedException("You shall not pass");
    }

    // the rest of the method etc etc
    // ...
}

... 其中 SomethingNotFoundExceptionNotAuthorizedException 是自定义的 Exception

在这种异常和 Http 状态代码(404 未找到/403 禁止)之间存在某种直接映射,我们希望我们的 Controller 方法相应地处理这些错误(显示404/403 CustomError 页面和类似的东西)。现在,我们想要的是避免在我们的 Controller 操作中执行此操作:

public ViewResult Get(int id){
    try{
        var theSomething = MyService.GetSomething(id, theUser);
    }
    catch(SomethingNotFoundException ex){
        throw new HttpException(404, ex);
    }
    catch(NotAuthorizedExceptionex){
        throw new HttpException(403, ex);
    }
}

我很确定一定有一种方法可以使用自定义 HandleErrorAttribute 或自定义 ActionFilterAttribute 并将其注册到 Global.asax 中,但我不知道如何让它工作。

尝试 1:HandleErrorAttribute

我首先尝试制作 HandleErrorAttribute 的子类,重写 OnException 方法:

public override void OnException(ExceptionContext filterContext)
{
    if (filterContext == null)
    {
        throw new ArgumentNullException("filterContext");
    }

    Exception exception = filterContext.Exception;
    // Map some of the Business Exception to correspounding HttpExceptions !
    if (exception is ObjectNotFoundException)
    {
        // consider it as a NotFoundException !
        exception = new HttpException((int)HttpStatusCode.NotFound, "Not found", exception);
        filterContext.Exception = exception;

    }
    else if (exception is NotAuthorizedException)
    {
        // consider it as a ForbiddenException 
        exception = new HttpException((int)HttpStatusCode.Forbidden, "Forbidden", exception);
        filterContext.Exception = exception;
    }

    base.OnException(filterContext);

}

... 并将其添加到 Global.asax 中的 GlobalFilterCollection ... 但它仍然被处理为就好像它是通常的 500 错误,而不是显示 404/403 自定义错误页面...

尝试 2:ActionFilterAttribute

我还尝试将其设为 ActionFilterAttribute 并重写 OnActionExecuted 方法,如下所示:

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
    if (filterContext == null)
    {
        throw new ArgumentNullException("filterContext");
    }
    Exception exception = filterContext.Exception;
    if(exception!=null)
    {
        // Map some of the Business Exception to correspounding HttpExceptions !
        if (exception is ObjectNotFoundException)
        {
            // consider it as a NotFoundException !
            var wrappingException = new HttpException((int)HttpStatusCode.NotFound, "Not found", exception);
            exception = wrappingException;
            filterContext.Exception = exception;
        }
        else if (exception is NotAuthorizedException)
        {
            // consider it as a ForbiddenException 
            var wrappingException = new HttpException((int)HttpStatusCode.Forbidden, "Forbidden", exception);
            exception = wrappingException;
            filterContext.Exception = exception;
        }
    }

    base.OnActionExecuted(filterContext);
}

...但是,我仍然得到 500 错误页面而不是 404 或 403 ...

我做错了什么吗?有没有更好的方法?

最佳答案

好吧,有几个选项。

你可能想要:This guys解决方案

你可以这样做This guy .

您可以拥有一个 Controller 基类,您的所有类都从该类继承并使用以下方法。这就是我上一家公司解决这个问题的方式。

protected override void OnException(ExceptionContext filterContext)
{
       Console.WriteLine(filterContext.Exception.ToString());
}

关于c# - 我怎样才能直接从我的特定于应用程序的异常映射到 Http 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12494841/

相关文章:

c# - Azure SQL 上的 Hangfire

asp.net-mvc - ASP.NET MVC 框架 4.5 CSS bundle 无法在托管上运行

jquery - 有没有一个好的方法来处理不显眼的验证看似异步的行为?

attributes - Nunit Action 属性构造函数被多次调用

asp.net-mvc - 路由参数、自定义模型绑定(bind)器或操作过滤器?

c# - ThreadStatic 和 ASP.NET

c# - 如何使用 C# 迭代 "Related Links"

c# - 我如何编码这个查询字符串?

c# - 我怎样才能让这个 ASP.NET MVC SelectList 工作?

asp.net-mvc-3 - 检查 Action 过滤器中的 ModelState