简体   繁体   English

如何避免重复为控制器中的每个操作发生的代码

[英]How to avoid duplicating code that occurs for every action in a controller

I have a controller which serves a number of pages. 我有一个控制器,可以提供多个页面。 Each Page has the following code block: 每个页面都有以下代码块:

public class SchoolController : Controller
{
    private UnitOfWork _unitOfWork = new UnitOfWork();

    public ActionResult Details()
    {
        var viewModel = new RegistryViewModel();

        School schoolBeingAccessed = _unitOfWork.SchoolRepository.GetLoggedinSchool();

        if (!schoolBeingAccessed.IsActive())
        {
            return RedirectToAction("NotActive");
        }
        if (!schoolBeingAccessed.IsExpired())
        {
            return RedirectToAction("Expired");
        }

        .....
   }

How can I best avoid duplicating this code? 我怎样才能最好地避免重复此代码? I can put this code into a function, but then I need to remember to call the function from every action in the controller. 我可以把这段代码放到一个函数中,但是我需要记住从控制器中的每个动作调用该函数。

Normally I would use something like Html.Action("CheckSchoolStatus") in the _Layout page, however I can't do that as I am redirecting, and you cannot redirect from a child action. 通常情况下,我会在_Layout页面中使用类似Html.Action(“CheckSchoolStatus”)的内容,但是当我重定向时,我无法做到这一点,并且您无法从子操作重定向。

Can I call this code from the Layout page? 我可以从布局页面调用此代码吗? Or should I use a base controller? 或者我应该使用基本控制器? How does that work if each View has it's own ViewModel? 如果每个View都拥有自己的ViewModel,那该怎么办?

You should use Action Filters . 您应该使用动作过滤器

From the documentation: 从文档:

Action filters. 动作过滤器。 These implement IActionFilter and wrap the action method execution. 这些实现IActionFilter并包装动作方法执行。 The IActionFilter interface declares two methods: OnActionExecuting and OnActionExecuted. IActionFilter接口声明了两种方法:OnActionExecuting和OnActionExecuted。 OnActionExecuting runs before the action method. OnActionExecuting在action方法之前运行。 OnActionExecuted runs after the action method and can perform additional processing, such as providing extra data to the action method, inspecting the return value, or canceling execution of the action method. OnActionExecuted在action方法之后运行,并且可以执行其他处理,例如向action方法提供额外数据,检查返回值或取消action方法的执行。

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

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