asp.net-mvc – 自动C#MVC错误处理

我有这个代码.

 public ActionResult Index()
 {
        ReceiptModel model = new ReceiptModel();

        try
        {
            model = new ReceiptModel(context);
        }
        catch (BussinessException bex)
        {
            ModelState.AddModelError("Index", bex.MessageToDisplay);
            return View("Index");
        }
        return View(model);
 }

BussinesException ir从数据库返回,然后显示给用户.我必须在每个控制器方法上加上try-catch语句,这有点单调乏味.有没有更简单的方法来处理这些异常?

附:使用HandleExceptionAttribute处理所有其他异常

更新:

我使用了Floradu88方法.所以现在我有这样的事情.

public sealed class HandleBussinessExceptionAttribute : HandleErrorAttribute, IExceptionFilter
    {

        public override void OnException(ExceptionContext filterContext)
        {
            filterContext.Controller.TempData["UnhandledException"] = filterContext.Exception;
            filterContext.ExceptionHandled = true;

            ((Controller)filterContext.Controller).ModelState.AddModelError(
                 ((BussinessException)filterContext.Exception).Code.ToString(),
                 ((BussinessException)filterContext.Exception).MessageToDisplay
             );

            filterContext.Result = new ViewResult
            {
                ViewName = this.View,
                TempData = filterContext.Controller.TempData,
                ViewData = filterContext.Controller.ViewData,
            };


        }
    }

以及我提出的控制器行动

[HandleBussinessExceptionAttribute(Order = 2, ExceptionType = typeof(BussinessException), View = "Login")]

我也试过异常处理程序:

 filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(filterContext.RouteData));

然后使用ModelState.IsValid处理错误操作,但操作的值为null.所以现在我使用第一种方法.当我有更多的时间,我会尝试修复第二种方法.

最佳答案 请阅读本部分的文档:

http://msdn.microsoft.com/en-us/library/gg416513%28v=vs.98%29.aspx

http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling

http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/understanding-action-filters-cs

要在此处发布的内容太多:

 public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute 
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            if (context.Exception is NotImplementedException)
            {
                context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
            }
        }
    }

而你的控制器:

public class ProductsController : ApiController
{
    [NotImplExceptionFilter]
    public Contact GetContact(int id)
    {
        throw new NotImplementedException("This method is not implemented");
    }
}
点赞