Thomas
Thomas

Reputation: 3368

Best way to deal with renaming a controller

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?

Upvotes: 3

Views: 2080

Answers (4)

JPA
JPA

Reputation: 77

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#)

Upvotes: 0

mrjoltcola
mrjoltcola

Reputation: 20862

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.

Upvotes: 2

J. Holmes
J. Holmes

Reputation: 18546

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.

Upvotes: 2

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()

Upvotes: 0

Related Questions