1

我有一个设置,我需要在多个函数中执行相同的代码。

[HttpGet]
public ActionResult Index()
{

    // Check if cookies are disabled, and redirect to login page if so
    if (cookiesDisabled(Request))
    {
        ModelState.AddModelError("cookie", "");
        return RedirectToAction("Login");
    }

    // Get the models
    AsdViewModel models = getAVM();
    if (models == null)
    {
        return Logout();
    }

    // Return view with the models passed in, etc.

}

public ActionResult OtherPage() {
    // Do cookie check so that just typing in MySite/Controller/OtherPage won't work
    // Get the models
    // Do some OtherPage() relevant calculations with the models
    // Return view with the models passed in, etc.
}

这里的问题是这段代码中有很多返回值。将 cookie 检查包装在布尔返回函数中似乎是多余的,因为我基本上只是保存一行 ( ModelState.Add...),并且与获取模型相同,因为我无法从内部函数调用中返回所有内容。有没有更好的方法来组织这个,或者我应该如何处理退货?

我知道我可以return OtherPage()在 Index 中执行类似的操作来跳过重复的代码,但我希望 URL 反映用户现在在OtherPage.

4

1 回答 1

0

您应该使用IActionFilter来检查用户是否已登录或您需要的任何其他 cookie。如果您有跨多个控制器的通用逻辑,则 IActionFilter 是有意义的(因为您可以使用相同的过滤器注释多个控制器)。

如果您只需要一个控制器中的通用逻辑,那么您可以覆盖在控制器上的操作之前调用的 OnActionExecuting 方法。

于 2013-09-27T14:35:08.857 回答