3

Working with ASP.NET MVC3, site is in beta and customer decided to rename one of the controllers.

http://domain.com/foo[/*] -> http://domain.com/bar[/*]

What is the most straightforward way to handle redirecting so I don't break any foo bookmarks?

Thomas
  • 3,348
  • 4
  • 35
  • 49

4 Answers4

2

Keep the old controller around so the old URLs still work.

Or add a rewrite rule. Something like:

domain.com/foo(/[_0-9a-z-]+)

to:

domain.com/bar{R:1}

URL Rewrite in IIS http://technet.microsoft.com/en-us/library/ee215194(WS.10).aspx http://www.iis.net/download/URLRewrite

If you are using MVC.NET you probably already have URL Rewrite installed.

codenheim
  • 20,467
  • 1
  • 59
  • 80
2

Another option would be to register a specific route for the old controller name in the Global.asax.cs.

routes.MapRoute(
    "RenamedController",                                              // Route name
    "[OldControllerName]/{action}/{id}",                           // URL with parameters
    new { controller = "[NewControllerName]", action = "Index", id = "" }  // Parameter defaults
);

Add that before the standard default route, and your new controller should respond to both old and new names.

J. Holmes
  • 18,466
  • 5
  • 47
  • 52
  • trying this because I hate IIS :) Will that redirect the id as written, or chop it off? – Thomas Aug 21 '11 at 04:25
  • Well, this approach isn't so much a redirect as two routes that go the same controller. Check out this URL for some better documentation: http://www.asp.net/mvc/tutorials/asp-net-mvc-routing-overview-cs – J. Holmes Aug 21 '11 at 04:29
  • Oh, interesting, it actually kept the old url instead of redirecting. Well, upvote for making me learning about MapRoute, but I don't think this satisfies my request. – Thomas Aug 21 '11 at 04:40
0

A 302 redirect would be fine, if you can figure out how to do that in IIS. This screenshot suggests it's not that arduous. Alternately, if you're using Castle Windsor you may want to register an interceptor that uses HttpResponse.Redirect()

0

REST standard suggests the best way to handle this issue is by returning a 301(Moved permanently request). Stack Overflow Post REST Standard

In .Net I recommend using Controller.RedirectToActionPermanent in your controller. See: ASP.NET, .NET Core

Code Example(should work for both ASP and Core):

public class MyController : ControllerBase
{
    public IActionResult MyEndpoint(string routeValues1, string routeValues2)
    {
        return RedirectToActionPermanent("action", "controller", new { value1 = routeValues1, value2 = routeValues2 });
    }
}

using MapRoute doesn't make sense in this case. MapRoute is really meant to provide a custom routing solution throughout the system. Its not really meant to deal with individual Redirects. As far as I'm aware it doesn't actually inform the user they are being redirected. See: Creating Custom Routes (C#)

JPA
  • 51
  • 6