I want to implement Exception Handling in my MVC project using the custom error attribute.
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.
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
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(){
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.