代码之家  ›  专栏  ›  技术社区  ›  Antoine Pelletier

如何重定向到函数内部的另一个操作

  •  0
  • Antoine Pelletier  · 技术社区  · 8 年前

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

    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 动作…当然,这没什么用。

    1 回复  |  直到 8 年前
        1
  •  3
  •   mjwills Myles McDonnell    8 年前

    我推荐一种如下的样式。 关键是回来 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;
    }
    
    推荐文章