0

How can I find the route that matches a string url in ASP.NET MVC?

This is not for the purposes of debugging.

I am generating a link using Request.UrlReferrer but we need to restrict this to specific controller actions in our application. Ideally we would so something like so:

@Url.PreviousUrl(
    default: Url.Action("index", "home")
    validRoutes: new[] { 
        new { controller = "list", "projects" }
        new { controller = "tagged", "projects" },
        new { controller = "details", "category" }
    }
);

If the UrlReferrer matches any of those routes then we will redirect to it, otherwise we will redirect to the default url specified.

Ben Foster
  • 34,340
  • 40
  • 176
  • 285
  • I think this question covers it http://stackoverflow.com/questions/3545432/how-to-get-routedata-by-url. I was trying to do the same thing and this answer solved it for me – GraemeMiller Jul 30 '14 at 14:55

1 Answers1

3

You can call GetRouteData as follows. There may be a better way, but I've used similar in unit testing

http://bradwilson.typepad.com/blog/2010/07/testing-routing-and-url-generation-in-aspnet-mvc.html

Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71
  • Thanks Adam - that did the trick. I thought maybe I could avoid stubbing/mocking http context but it seems clean enough. I've posted my currently hacky/poorly tested code at https://gist.github.com/2346138 :) – Ben Foster Apr 09 '12 at 19:53
  • You do have a ref to the current httpcontext, what happens if you use it - i.e. what prevents you from using it? – Adam Tuliper Apr 10 '12 at 22:28
  • Hi Adam. If I use the current HttpContext, the 'HttpContext.Request.Url' (readonly) is set to the current page. I need to build a HttpContext for the **previous** page url (the one I am checking) to see if it matches specific routes. Does that make sense? – Ben Foster Apr 11 '12 at 12:02
  • ah ya, you did state the referrer : ) – Adam Tuliper Apr 11 '12 at 14:11
  • Consider updating this answer with details from the post you linked instead of just redirecting. Answers with just a link may become invalid later when the link is broken. – julealgon Jan 05 '17 at 13:09