0

I'm testing a condition with a session object and if it's false, I need to redirect somewhere. I'd like to make a function out of it. Normally I would have :

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
}

But I began have a lot of these in every action... I feel like this is somehow wrong and I would like to put them all in a function so I can focus on 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");
}

When RedirectToAction is not returned by an ActionResult fonction... it doesn't do anything, of course.

Antoine Pelletier
  • 3,164
  • 3
  • 40
  • 62
  • 3
    Change `void` to `ActionResult`. Have `SomeAction` check whether the result is `null` and if it isn't, return it. `var bob = MaybeRedirect(); if (bob != null) return bob;` – mjwills Jul 13 '18 at 13:07
  • 1
    And as an alternative and to get rid of this if-else series, you could use a `Dictionary` like this https://stackoverflow.com/a/42505360/2946329 – Salah Akbari Jul 13 '18 at 13:09
  • @S.Akbari interesting... but i can't figure it out with my exemple. – Antoine Pelletier Jul 13 '18 at 13:14
  • @mjwills You just opened my eyes with your comment, it runs the function only once and the var contains the potential action result... brilliant. Will you make this an answer ? – Antoine Pelletier Jul 13 '18 at 13:22

1 Answers1

3

I would recommend a pattern like below. The key thing is returning null to indicate "please don't redirect".

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;
}
mjwills
  • 23,389
  • 6
  • 40
  • 63