简体   繁体   English

向所有操作添加默认参数

[英]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 所以我创建了这个BaseController,我的所有控制器都将从该BaseController继承

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. 如您所见,我想检查用户是否在URL中请求了促销ID。 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. 问题是,为了使此工作正常进行,我必须在所有动作中添加一个参数promotionId (即更改所有动作的签名),而我不想这样做。

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 ? 还是有更好的方法来做到这一点?

You don't have to add promotionId parameter in all your actions. 您不必在所有操作中都添加promotionId参数。 You can check if the url has this parameter using the Request property of your controller. 您可以使用控制器的Request属性检查url是否具有此参数。

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);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM