Tuesday, April 5, 2011

ASPNET MVC: Way to figure out the route of the referer (sic)?

I have some POST actions on my controller that are hit from a pair of GET actions. When validation fails, I want to render the view of the action that the POST is coming from. For example:

~/accounts POSTs to ~/accounts/disable - render "index" view on validation error ~/accounts/profile POSTs to ~/accounts/disable - render "profile" view on validation error

I can get the referer (sic) out of server-variables and parse it to figure out the action, but was hoping there would either be something built in that does what I want, or someone else has already done this that I could crib from.

It seems the ControllerContext.RouteData property only has information about the current request, not the refering (sic) request...?

I'm on ASP.NET MVC beta.

From stackoverflow
  • MVC Contrib includes an extension method on String to get a route (specifically, in here). In theory this would let you do

    RouteData referrer = Request.UrlReferrer.PathAndQuery.Route();
    

    or, of course, wrap that up in an extension method on HttpRequest so you can just do

    RouteData referrer = Request.ReferrerRoute();
    

    However, it's intended for unit testing and uses Rhino Mocks to create the HttpContextBase that GetRouteData() requires. The good news is that it seems to get away with mocking very little of it, so you might be able to avoid Rhino Mocks if you create your own FakeHttpContext class derived from HttpContextBase.

0 comments:

Post a Comment