Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stackoverflow style URL (customising outgoing URL)

If I navigate to the following stackoverflow URL http://stackoverflow.com/questions/15532493 it is automatically appended with the title of the question like so:

http://stackoverflow.com/questions/15532493/mvc-custom-route-gives-404

That is, I can type the URL into my browser without the question title and it is appended automatically.

How would I go about achieving the same result in my application? (Note: I am aware that the question title doesn't affect the page that is rendered).

I have a controller called Users with an action method called Details. I have the following route defined:

routes.MapRoute("UserRoute",
    "Users/{*domain}",
     new { controller = "User", action = "Details" },
     new { action = "^Details$" });

As this is an intranet application the user is authenticated against their Windows account. I want to append the domain and user name to the URL.

If I generate the URL in the view like so:

@Html.ActionLink("Model.UserName", "Details", "User", new { domain = Model.Identity.Replace("\\", "/") })

I get a URL that look like this:

Domain/Users/ACME/jsmith

However, if the user navigates to the URL Domain/Users/ by using the browsers navigation bar it matches the route and the user is taken to the user details page. I would like to append the ACME/jsmith/ onto the URL in this case.

The research I have done so far indicates I might have to implement a custom route object by deriving from RouteBase and implementing the GetRouteData and GetVirtualPath methods but I do not know where to start with this (the msdn documentaiton is very thin).

So what I would like to know is:

  1. Is there a way of achieving this without implementing a custom route?
  2. If not, does anyone know of any good resources to get me started implementing a custom route?
  3. If a custom route implementation is required, how does it get at the information which presumably has to be loaded from the database? Is it OK to have a service make database calls in a route (which seems wrong to me) or can the information be passed to the route by the MVC framework?
like image 979
Benjamin Gale Avatar asked Apr 09 '13 14:04

Benjamin Gale


2 Answers

It's actually pretty simple. Since the title is just there for SEO reasons you do not need to get to the actual question, so the Question controller (in SO case) will load the correct question based on the id (in the URL) and redirect the user with a 301 status code.

You can see this behavior with any web inspector

enter image description here

like image 113
tucaz Avatar answered Sep 30 '22 03:09

tucaz


You could do it client-side with Javascript:

history.pushState({}, /* Title Here */, /* URL Here */ );

Only downside is not all browsers support it.

like image 29
Joey Gennari Avatar answered Sep 30 '22 05:09

Joey Gennari