Reputation: 39916
I have a website and I want
/22 Redirect to
/user/22
etc and so on, however there are other mvc views and controllers and they all work alright, I have used following Route but its not working.
routes.MapRoute(
"Final",
"{id}",
new { controller = "Root", action = "Index"},
new { id = @"\d+" },
new string[] { "MyWebApp.Controllers" }
);
Ideally this route should only work if url fragment is numeric.
I have a RootController in MyWebApp.Controllers namespace as well. And all it does is redirect to other page as below,
public class RootController : Controller
{
public ActionResult Index(long id) {
return RedirectPermanent("/user/" + id);
}
}
Now, we have to do this because it is an upgrade to old website and we cannot change url scheme, because its public and in use.
Note: URLs /user/22 etc are working correctly, only this root URL is giving problem.
Upvotes: 1
Views: 588
Reputation:
I have tested this route out:
routes.MapRoute(
"Final",
"{id}",
new { controller = "Root", action = "Index" },
new { id = @"\d+" }
);
It is working just as it should. But if you're having an issue with it, I'm guessing that your desired URL is matching another route prior to it. Put this route as your first route and see if that fixes it.
For instance, if your routes look like this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Final",
"{id}",
new { controller = "Root", action = "Index" },
new { id = @"\d+" }
);
You will get a 404 resource not found. But if you switch them like this:
routes.MapRoute(
"Final",
"{id}",
new { controller = "Root", action = "Index" },
new { id = @"\d+" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Then you'll get the desired routing with a request like /1234
.
Upvotes: 2