【发布时间】: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