How to achive MVC route with numbers

I am trying to route an old URL that is domain.com/1024 to my home page in mvc.

I keep getting resource not found errors.

Here is my routeConfig

        routes.MapRoute(
        name: "1024",
        url: "{controller}/{action}",
        defaults: new { controller = "Home", action = "Direct", id = UrlParameter.Optional }
    );

 My Controller 

    public ActionResult Direct()
    {
 
        return RedirectToAction("Index");
    }

Last updated:12/26/2014 7:14:32 AM

1 Answers

Anonymous User
Anonymous User

Hi jay

If you have your route definition before the default, for example:

routes.MapRoute(
  name: '1024',
  url: '{id}',
  defaults: new { controller = 'Home', action = 'Direct' }
);
routes.MapRoute(
  name: 'Default',
  url: '{controller}/{action}/{id}',
  defaults: new { controller = 'Home', action = 'Index', id = UrlParameter.Optional }
);
This will route (host):(port)/ to Index and (host):(port)/1024 to Direct where you can RedirectToAction('Index').

For example a HomeController to demonstrate the point (This ONLY redirects 1024 to index):

public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Direct(int? id)
        {
            if (id.HasValue && id.Value == 1024)
            {
                return RedirectToAction('Index');
            }
            else
            {
                return View();
            }
        }
    }
This would redirect any id to index:

public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Direct(int? id)
        {
            return RedirectToAction('Index');
        }
    }

Answer