如何在MVC中挂钩调用控制器操作?

时间:2022-12-01 23:11:50

In my MVC3 application I have lots of controllers and actions. Sometimes an exception is raised while executing an action. I want to be able to log that and let the exception be handled by MVC.

在我的MVC3应用程序中,我有很多控制器和操作。有时在执行操作时会引发异常。我希望能够记录它并让MVC处理异常。

Something like this pseudocode:

像这样的伪代码:

try {
    MvcInvokeControllerAction( controller, action, params );
} catch( Exception e ) {
    trace( "Error while invoking " + controller + "-" +
       action + " with " + params + " details: " + getDetails( e ) );
    throw;
}

What I want is to be able to catch the exception before it is first processed by MVC because sometimes MVC kicking in raises another exception and I see the latter in Application_Error() and the original exception is lots.

我想要的是能够在MVC首次处理之前捕获异常,因为有时MVC踢入会引发另一个异常,我在Application_Error()中看到后者,原始异常很多。

How do I achieve such hooking?

我如何实现这样的挂钩?

1 个解决方案

#1


1  

You can override OnException Method On your Basecontrollor.

您可以在Basecontrollor上覆盖OnException方法。

This will be a Catch block for all exceptions in Controllor Actions. just Exetnd all your Controllors from Basecontrollor

这将是Controllor操作中所有异常的Catch块。只需从Basecontrollor中取出所有控制器

protected override void OnException(ExceptionContext filterContext)
{
}

Example

public class BaseController : Controller
{

    protected override void OnException(ExceptionContext filterContext)
    {
        base.OnException(filterContext);
        // Handle error here
    }
}


public class TestController : BaseController
{
    public ActionResult Index()
    {
        // If any exceptions then will be caught by 
        // BaseController OnException method
    }
}

#1


1  

You can override OnException Method On your Basecontrollor.

您可以在Basecontrollor上覆盖OnException方法。

This will be a Catch block for all exceptions in Controllor Actions. just Exetnd all your Controllors from Basecontrollor

这将是Controllor操作中所有异常的Catch块。只需从Basecontrollor中取出所有控制器

protected override void OnException(ExceptionContext filterContext)
{
}

Example

public class BaseController : Controller
{

    protected override void OnException(ExceptionContext filterContext)
    {
        base.OnException(filterContext);
        // Handle error here
    }
}


public class TestController : BaseController
{
    public ActionResult Index()
    {
        // If any exceptions then will be caught by 
        // BaseController OnException method
    }
}