Antoine Pelletier
Antoine Pelletier

Reputation: 3316

How to redirect to another action inside a function

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.

Upvotes: 0

Views: 659

Answers (1)

mjwills
mjwills

Reputation: 23898

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;
}

Upvotes: 3

Related Questions