【问题标题】:How to redirect to another action inside a function如何重定向到函数内的另一个动作
【发布时间】:2018-07-13 13:05:11
【问题描述】:

我正在使用会话对象测试条件,如果它为假,我需要重定向到某个地方。我想用它做一个功能。通常我会:

public ActionResult SomeAction()
{
    if (Session["level"] == null)
        return RedirectToAction("Home", "Whatever");

    if ((int)Session["level"] == 1)
        return RedirectToAction("Choose", "Whatever");

    // The rest of the code
}

但是我开始在每个动作中都有很多这样的东西......我觉得这有点不对劲,我想把它们都放在一个函数中,这样我就可以专注于the rest of the code

public ActionResult SomeAction()
{
    MaybeRedirect();

    // The rest of the code
}

public void MaybeRedirect()
{
    if (Session["level"] == null)
        return RedirectToAction("Home", "Whatever");

    if ((int)Session["level"] == 1)
        return RedirectToAction("Choose", "Whatever");
}

RedirectToAction 没有被ActionResult 函数返回时......当然,它什么也不做。

【问题讨论】:

  • void 更改为ActionResult。让SomeAction 检查结果是否为null,如果不是,则返回。 var bob = MaybeRedirect(); if (bob != null) return bob;
  • 作为替代方案并摆脱这个 if-else 系列,您可以使用 Dictionary 这样的 stackoverflow.com/a/42505360/2946329
  • @S.Akbari 很有趣......但我无法用我的例子来弄清楚。
  • @mjwills 你刚刚用你的评论让我大开眼界,它只运行了一次函数,并且 var 包含潜在的操作结果......太棒了。你会回答这个问题吗?

标签: c# asp.net-mvc redirect


【解决方案1】:

我会推荐如下模式。 关键是返回null 表示“请不要重定向”。

public ActionResult SomeAction()
{
    var predefinedRedirect = MaybeRedirect();

    if (predefinedRedirect != null)
        return predefinedRedirect;

    // The rest of the code
}

private ActionResult MaybeRedirect()
{
    if (Session["level"] == null)
        return RedirectToAction("Home", "Whatever");

    if ((int)Session["level"] == 1)
        return RedirectToAction("Choose", "Whatever");

    ... // other conditions here

    return null;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-25
    • 2010-10-07
    • 2015-08-09
    • 2011-06-22
    • 2015-03-03
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多