views:

1469

answers:

1

Hi,

We're currently running on IIS6, but hoping to move to IIS 7 soon.

We're moving an existing web forms site over to ASP.Net MVC. We have quite a few legacy pages which we need to redirect to the new controllers. I came across this article which looked interesting: http://blog.eworldui.net/post/2008/04/ASPNET-MVC---Legacy-Url-Routing.aspx

So I guess I could either write my own route handler, or do my redirect in the controller. The latter smells slightly.

However, I'm not quite sure how to handle the query string values from the legacy urls which ideally I need to pass to my controller's Show() method. For example:

Legacy URL: /Artists/ViewArtist.aspx?Id=4589

I want this to map to: ArtistsController Show action

Actually my Show action takes the artist name, so I do want the user to be redirected from the Legacy URL to /artists/Madonna

Thanks!

+6  A: 

depending on the article you mentioned, these are the steps to accomplish this:

1-Your LegacyHandler must extract the routes values from the query string(in this case it is the artist's id) here is the code to do that:

 public class LegacyHandler:MvcHandler
    {
        private RequestContext requestContext;
        public LegacyHandler(RequestContext requestContext) : base(requestContext)
        {
            this.requestContext = requestContext;
        }

        protected override void ProcessRequest(HttpContextBase httpContext)
        {
            string redirectActionName = ((LegacyRoute) RequestContext.RouteData.Route).RedirectActionName;

            var queryString = requestContext.HttpContext.Request.QueryString;
            foreach (var key in queryString.AllKeys)
            {
                requestContext.RouteData.Values.Add(key, queryString[key]);
            }

            VirtualPathData path = RouteTable.Routes.GetVirtualPath(requestContext, redirectActionName,
                                                                    requestContext.RouteData.Values);
            httpContext.Response.Status = "301 Moved Permanently";
            httpContext.Response.AppendHeader("Location", path.VirtualPath);

        }
    }

2- you have to add these two routes to the RouteTable where you have an ArtistController with ViewArtist action that accept an id parameter of int type

    routes.Add("Legacy", new LegacyRoute("Artists/ViewArtist.aspx", "Artist", new LegacyRouteHandler()));

    routes.MapRoute("Artist", "Artist/ViewArtist/{id}", new
        {
         controller = "Artist",
         action = "ViewArtist",
        });

Now you can navigate to a url like : /Artists/ViewArtist.aspx?id=123

and you will be redirected to : /Artist/ViewArtist/123

Marwan Aouida
Hi, cool thanks for this.FYI, so that I could a 301 redirec to the new style of url:artists/<ArtistName> as opposed to ID, I created a new ActionResult called RedirectLink which redirected the link via a 301 to the new format.Thanks
Perhentian