C# 从多个函数中的嵌套函数返回

C# 从多个函数中的嵌套函数返回,c#,asp.net-mvc-4,C#,Asp.net Mvc 4,我有一个设置,需要在多个函数中执行相同的代码 [HttpGet] public ActionResult Index() { // Check if cookies are disabled, and redirect to login page if so if (cookiesDisabled(Request)) { ModelState.AddModelError("cookie", ""); return RedirectToAc

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

[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…,获取模型也是如此,因为我无法从内部函数调用返回所有内容。我有没有更好的方法来组织这件事,或者我应该如何处理回报

我知道我可以做一些类似于在索引中返回OtherPage的事情来跳过重复的代码,但我希望URL能够反映用户现在在OtherPage中。

您应该使用来检查用户是否登录,或者是否需要cookie。如果您在多个控制器之间具有公共逻辑,则IActionFilter是有意义的,因为您可以使用同一个筛选器注释多个控制器


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

谢谢,这似乎就是我想要的。但是我该如何处理得到这些模型呢?如果我以后需要在函数中使用对象,那么它不可能成为过滤器的一部分吗?如果重写控制器的OnActionExecuting方法,则getAVM方法应该可用。如果您正在实现一个过滤器,那么您应该能够在过滤器中移动getAVM方法中的逻辑并在那里调用它。我的意思是如何访问从该过滤器获得的模型,但我在别处找到了答案,只需要设置filterContext.Controller.ViewData.model。不过,感谢您向我介绍ActionFilter,我以前从未研究过它。