2

我正在做一个 MVC 项目,我从 NerdDinner 项目中复制了很多工作。在 NerdDinner 中,如果没有找到晚餐或用户不是晚餐的所有者,我们将返回一些视图,例如 DinnerNotFound、InvalidOwner。但是在我的项目中想要创建一个视图(CustomException)并出于所有这些原因使用它。所以我提出异常并在我的 basecontrller 的 OnException 事件中捕获它们。然后从那里我想在将其登录到 ELMAH 后呈现自定义视图。

但是渲染该视图的调用 (RedirectToAction("CustomException",ce );) 似乎不起作用,它不会导航到操作 CustomException。

有人可以帮助我可能是什么原因。我在这里列出了所有文件。另外我应该如何进入 global.asax.cs 文件。代码如下。

问候帕米德

列表异常.cs

命名空间Listing.Exceptions { 公共静态类ListingExeceptions {

    public static CustomException GetCustomException(Exception ex)
    {
        CustomException ce = new CustomException();
        switch (ex.Message)
        {
            case ItemConstant.INVALID_OWNER:
                ce = new CustomException("Invalid Owner", "OOps you are not owner of this item");
                break;
            case ItemConstant.ITEM_NOT_FOUND:
                ce = new CustomException("Item not Found", "The Item you are looking for couldnt be found");
                break;
            default:
               ce = new CustomException("Error ", "There is an Error.");
               break;
        }

        return ce;

    }


}

}

基本控制器.cs

命名空间Listing.Controllers {公共部分类BaseController:控制器{

    public virtual ActionResult CustomException(CustomException ce)
    {
        return View(ce);   
    }

    protected override void OnException(ExceptionContext filterContext)
    {
        base.OnException(filterContext);

        CustomException ce = ListingExeceptions.GetCustomException(filterContext.Exception);
        ErrorSignal.FromCurrentContext().Raise(filterContext.Exception);
        filterContext.ExceptionHandled = true;

        RedirectToAction("CustomException",ce );
    }
}

}

清单控制器.cs

命名空间Listing.Controllers

{

public virtual ActionResult Details(long id, string title) {

        Item item = itemRepository.GetItemByID(id);

        if (item == null)

        {

            throw new Exception("ItemNotFound");

        }

        else

        {

            return View("Details", new ListingFormViewModel(item, photoRepository));

        }
    }

}

全局.asax.cs

routes.MapRoute( "Exception", // 路由名称 "{controller}/{action}/{ce}", // 带有参数的 URL new { controller = "Base", action = "CustomException", ce = "" } );

4

1 回答 1

1

我不太确定您是否可以在OnException. 添加一个filterContext.Result =应该工作:

protected override void OnException(ExceptionContext filterContext)
{
    base.OnException(filterContext);

    CustomException ce = ListingExeceptions.GetCustomException(filterContext.Exception);
    ErrorSignal.FromCurrentContext().Raise(filterContext.Exception);
    filterContext.ExceptionHandled = true;

    filterContext.Result = RedirectToAction("CustomException",ce );
}
于 2009-07-26T04:54:09.717 回答