简体   繁体   中英

Is there any way to override a MVC Controller Action?

I am adapting an open source project (NopCommerce). It is a great software and supports extensibility using plugins. For one plugin, I would like to add information to a view, to do that, I want to inherit from the Controller and override the actions I need to change. So this is my controller:

public class MyController : OldController{
//stuff

public new ActionResult Product(int productId)
{
 //Somestuff
}

}

I changed the route from my plugin, but when this action get called I get the following error:

The current request for action 'Product' on controller type 'MyController' is ambiguous between the following action methods: System.Web.Mvc.ActionResult Product(Int32) on type MyPlugin System.Web.Mvc.ActionResult Product(Int32) on type OldController

Is there any way I can override this method? (ps: I can't use the override keyword because it is not marked as virtual, abstract or override in the OldController)

thanks, Oscar

If OldController's method is few, Redeclare like this.

public class MyController : Controller 
{
    private OldController old = new OldController();

    // OldController method we want to "override"
    public ActionResult Product(int productid)
    {
        ...
        return View(...);
    }

    // Other OldController method for which we want the "inherited" behavior
    public ActionResult Method1(...)
    {
        return old.Method1(...);
    }
}

sure, "do a F12" on the controller and look at the items marked virtual

    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (Request.Headers.TryGetValue("myHeader", out var value))
        {
            HashId = hashid.ToString();
        }
        base.OnActionExecuting(context);
    }

Just Change

    public class MyController : OldController{
    //stuff

        public new ActionResult Product(int productId)
        {
        //Somestuff
        }
    }

to

    public class MyController : OldController{
    //stuff

        public override ActionResult Product(int productId)
        {
        //Somestuff
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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