Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Asp.Net MVC OnActionExecuting To Redirect Action

Posted on: 2014-08-21

Asp.Net MVC allows you to catch Http Request by overriding the OnActionExecuting and takes a decision before executing the desired Controller-Action method. This can be interesting in the case you want to verify something and if this validation is wrong to redirect the user.

A small use case could be that your user that have to be part of a team/contest/group and if this one is not, than we redirect to a message. Instead of having in all your action the validation to see if the user belong to the group, it is simpler and less repetitive to have in your controller the OnActionExecuting overrided.

Here is an example in .Net.

 protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); if (this.RouteData != null && this.RouteData.Values.ContainsKey(Constants.RoutePortionName.ACTIVE_CURRENT_CONTEST_ID)) { var success = SetCurrentActivePortefolioByContestId(Convert.ToInt32(this.RouteData.Values[Constants.RoutePortionName.ACTIVE_CURRENT_CONTEST_ID])); if (!success)
 //This is the case when the user does not belong to the contest but try to do an action on the contest 
 filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary { { Constants.AREA, Constants.Areas.ERRORS }, { Constants.CONTROLLER, "UserError" }, { Constants.ACTION, "InvalidContest" } }); } } else { this.CurrentActivePortefolio = null; } } 

First, we call the base class to continue to normal behavior of the execution but after we do the logic. The first condition statement verify that in the URL we have the Contest ID defined. If yes, than we are trying to execute an action on the Contest (which is a group or a team or anything you want). If it is set, we need to verify if the user belong to this group. This is done by calling the method SetCurrentActivePortefolioByContestId. This method call the database with the Id of the Contest and the Id of the User. If the database return an entry from the database this mean that you have a match and we do not redirect. Otherwise, we redirect. This is where something must be done more than just calling RedirectToAction. In fact, we have to change the current execution context values. As you may have seen, the OnActionExecution has a single parameter. This parameter has a Result property that can be defined with the Area, Controller and Action you desired. In the example, this is where we redirect the user into the Errors area.