简体   繁体   English

使用HandleErrorAttribute在MVC中进行异常处理

[英]Exception Handling in MVC using HandleErrorAttribute

I want to implement Exception Handling in my MVC project using the custom error attribute. 我想使用自定义错误属性在我的MVC项目中实现异常处理。

The 4th example provided here is incomplete in terms of where we should enter view name, a controller name, etc and how to decorate the controllers and action with the new attribute. 提供的4例子这里是的,我们应该进入视图名称,控制器名称等,并如何装饰控制器和行动统一到新的属性方面不完整的。

Any help would be appreciated. 任何帮助,将不胜感激。

Create the custom error attribute as such 这样创建自定义错误属性

public class MyCustomErrorAttribute : HandleErrorAttribute
{
       public override void OnException(ExceptionContext filterContext)
        {
            var controllerName = filterContext.RouteData.Values["controller"];
            var actionName = filterContext.RouteData.Values["action"];
            //Do something with the Controller or Action, e.g. Logging the exception
            base.OnException(filterContext);
        }
    }

Then add the following code into the Global.asax.cs 然后将以下代码添加到Global.asax.cs

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(MyCustomErrorAttribute);
} 

Then simply use the attribute on the controller level as such 然后,只需在控制器级别使用属性即可

[MyCustomErrorAttribute]
public class HomeController: Controller
{

}

or on the action method level as such 或在动作方法级别上

public class HomeController: Controller
{
    [MyCustomErrorAttribute]
    public ActionResult Index(){

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM