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?
views:
134answers:
3
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
2009-12-11 13:45:48
+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
2009-12-11 13:48:04
+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
2009-12-11 13:54:54
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
2009-12-11 13:58:46
Thanks for the highlighting that caveat Craig
Rob Levine
2009-12-11 14:14:53
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
2009-12-11 14:20:14