How can I use RedirectToAction within a base controller class?
Right n开发者_运维百科ow I'm in the process of converting a web application to an MVC 2 website. I have a base controller which all my other controllers inherit from. I have some business logic I've placed in an overridden Execute method that, if need be, will redirect a user to an action.
Every controller action needs to run this same logic and I didn't want to put calls to my function in every action method. I wanted a central place to place the code. In the old website I had this logic run within a master page load event, but transitioning this logic to MVC 2 has been challenging.
You need to call the ExecuteResult
method on the returned ActionResult
.
Also, you should override ExecuteCore
, not Execute
. Otherwise, you lose the ControllerContext
.
By the way, you should consider writing an ActionFilter and loading it dynamically.
Depending on when the code needs to run, you can override the OnActionExecuting and/or OnActionExecuted methods in your base controller class.
Just simply put below code in your every controllers. (Before Construction)
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
//You function here
}
Please remember to write your function in one class. if there's any modification occurs, you don't have to change the controllers again.
精彩评论