2013-02-20 36 views
5

我正在调整一个开源项目(NopCommerce)。它是一款优秀的软件,支持使用插件的可扩展性。 对于一个插件,我想将信息添加到视图中,为此,我想从Controller继承并覆盖需要更改的操作。 所以这是我的控制器:有什么方法来重写MVC控制器操作?

public class MyController : OldController{ 
//stuff 

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

} 

我从我的插件改变了路线,但是当这个动作被调用我得到以下错误:

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

有什么办法,我可以重写此方法? (PS:我不能使用override关键字,因为它没有标记为虚,在OldController抽象或重写)

感谢, 奥斯卡

+1

如何不从'OldController' _deriving_而是提供所有的'OldController'方法裹在你的'MyController'类(一种类似于[代理模式(http://www.dofactory.com /Patterns/PatternProxy.aspx#_self1)) – 2013-02-20 02:19:17

+0

如果它被标记为虚拟它会起作用吗?我曾经以一种不正当的方式想到你曾经有过什么工作 – Rikon 2013-02-20 02:22:39

+0

你想实现什么,从目前的Controller类不容易扩展? – 2013-02-20 02:23:18

回答

6

如果OldController的方法是少,重复声明是这样的。

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(...); 
    } 
} 
+1

是的,这是一个很好的出路,@Uwe Kleim在评论中提出了它。 DaveA听起来是因为他有很好的洞察力,所以我会在尝试这个之前检查他的想法:) – JSBach 2013-02-20 02:48:36

+1

@Oscar,根据您的需要,我会建议从Controller类继承一个完全按照ebattulga的方式。这是你正在寻找的方法! ;) – 2013-02-20 02:56:34

+1

@DaveA非常感谢! – JSBach 2013-02-20 02:57:29

相关问题