views:

134

answers:

3

Is there any easy way to distinguish between an ASP.NET MVC controller action being hit "directly" due to a client web browser request, and being hit by virtue of a Controller.RedirectToAction call or a RedirectToRoute result?

A: 

Request.ServerVariables["http_referrer"] would be empty if is the action is hit from a redirect to action, I think. Otherwise it would be the URL that corresponds to the action method visited "directly".

Kindness,

Dan

Daniel Elliott
+1  A: 

You may have the option of adding a parameter to your Action method that allows you to pass in a value specifying whether it's a Controller.RedirectToAction, a RedirectToRoute, or a client browser request. Couple this with some server variable checks and you may be able to come up with something that works most of the time.

public ActionResult MyAction(string source)
{
    if (source == "")
    {
        // client browser request
    }
    else if (source == "redirectToAction")
    {
        // redirect to action
    }
    else if (source == "redirectToRoute")
    {
        // redirect to route
    }
}
Tim S. Van Haren
+1  A: 

Alternatively, put a value in TempData

public class SomeController : Controller
{
    public ActionResult SomeAction()
    {
        // ... do stuff ...
        TempData["SomeKey"] = "SomeController.SomeAction";
        return RedirectToAction("SomeOtherAction", "SomeOtherController");
    }
}

public class SomeOtherController : Controller
{
    public ActionResult SomeOtherAction()
    {
        if (TempData.ContainsKey("SomeKey"))
        {
            // ... do stuff ...
        }
        // etc...
    }
}

(From Craig Stuntz)

Jarrett Meyer
This would work fine for MVC 1, but might be fragile in MVC 2. MVC 2 won't clear the key until you read it, so if you "forgot" to read it somewhere then there might be a "stale" key in the session.
Craig Stuntz
Thanks for the highlighting that caveat Craig
Rob Levine
Ah, so ASP.NET MVC's TempData is going to catch up to Rails' "flash hash"? Very nice! I'm liking a lot coming out of MVC 2.
Jarrett Meyer