Home > DeveloperSection > Forums > How to achive MVC route with numbers
Chintoo Semi

Total Post:135

Points:947
Posted on    December-26-2014 5:43 AM

 ASP.Net C#  ASP.NET MVC  Routing 
Ratings:


 1 Reply(s)
 519  View(s)
Rate this:

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");

    }



Pravesh Singh
Pravesh Singh

Total Post:101

Points:709
Posted on    December-26-2014 7:14 AM

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");
        }

    }

Modified On Apr-12-2016 12:16:06 AM

Don't want to miss updates? Please click the below button!

Follow MindStick