Search code examples
c#asp.netasp.net-mvc-4routesaction-filter

Add a default parameter to all actions


I want to add certain methods and I want them to be executed before executing any action. So I created this BaseController from which all my controllers will inherit

public class BaseController : Controller
{
    protected int promotionId = 0;

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        bool thereIsPromo = false;
        if (filterContext.ActionParameters.Keys.Contains("promotionId"))
        {
            thereIsPromo = true;
        }

        var foo = filterContext.RouteData;
        // TODO: use the foo route value to perform some action

        base.OnActionExecuting(filterContext);
    }

}

As you can see I want to check if the user has requested a promotion Id in the URL. The problem is, in order to get this working, I have to add a parameter promotionId to all my actions (meaning change the signature of all my actions) and I don't want to do that.

Is there a way to override the default action method and add an optional parameter to it so it would be added to all my actions ?

Or is there a better way to do this ?


Solution

  • You don't have to add promotionId parameter in all your actions. You can check if the url has this parameter using the Request property of your controller.

    public class BaseController : Controller
    {
        protected int promotionId = 0;
    
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            bool thereIsPromo = false;
    
            // Check if the request has the paramter PromotionId
            if (Request.Params.AllKeys.Contains("promotionId"))
            {
                promotionId = int.Parse(Request["promotionId"]);
                thereIsPromo = true;
            }
    
            var foo = filterContext.RouteData;
            // TODO: use the foo route value to perform some action
    
            base.OnActionExecuting(filterContext);
        }
    
    }