【发布时间】:2018-05-17 17:02:10
【问题描述】:
我想实现一个 BaseController Action 方法,该方法在 Controller 类的 Action 之前或之后被调用,用于在 View 渲染到 Razor 之前对其进行修改。
public class BaseViewModel
{
public BaseViewModel() {}
public string Property1 {get; set;}
}
public class ViewModel : BaseViewModel
{
public ViewModel () : base() {}
// Some View Methods
}
public class BaseController
{
public BaseController();
// here is where I want to put code to intercept the call to the
// AccountController when any action is performed and write to the
// Property1 of the Base class of the ViewModel class.
}
public class AccountController : BaseController
{
public AccountController() : base() {}
public IActionResult About()
{
return(new ViewModel());
}
}
我不知道该怎么做我试图解释的事情,或者它是否可以实现。 我能得到一些反馈或建议吗?
BaseViewModel 将包含对所有页面更通用的属性,例如 Culture、Title 等,并且与 ViewModel 完全无关,但可能会在 View 上呈现。
【问题讨论】:
-
您需要查看操作过滤器docs.microsoft.com/en-us/aspnet/core/mvc/controllers/… 以在操作之前和之后执行代码
-
它会考虑把它放在马特所说的地方,但把行为放在一个单独的类中,而不是从基本控制器继承。继承并不是多个类共享一个行为的最佳方式。它变得复杂,因为如果你想要另一个“基本”行为,你把它放在基类中,但是如果不是每个控制器都应该有其他行为呢?这个问题是通过优先组合而不是继承来解决的。继承就像黑暗的一面。一旦你走上这条路,它就会永远主宰你的命运。
标签: c# asp.net-core-mvc