BaseController ASPCore MVC

时间:2018-05-17 17:02:10

标签: c# asp.net-core-mvc

我想实现一个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上进行渲染。

1 个答案:

答案 0 :(得分:2)

您应该能够覆盖OnActionExecuting:

// Custom Base controller.
public class BaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Do whatever here...
    }
}

// Account controller.
public class AccountController : BaseController
{
    // Action methods here...
}