3

I have a website that need a departmentID for all sites, so i rewrote the default route to the following:

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

It works fine when you for example use the following URL:

http://domain/2/Home/Index

or just simply:

http://domain/2

My problem is that when i go to "http://domain/" i get an error because i dont have specified the departmentID. How can i add a second route which will fire when you just go to the domain.

I have tried to add the following:

routes.MapRoute(
            name: "Start",
            url: "/",
            defaults: new { controller = "Department", action = "Select"}
        );

Which doesnt work since you cant just put "/" as an URL.

I have also tried to add the default route and then just change the defaults object:

            routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Department", action = "Select", id = UrlParameter.Optional }
        );

This doesnt work either.

Michael Kirkegaard
  • 379
  • 1
  • 3
  • 14
  • What error you get in the first place? Since you provided a default value for `deptID` in the `defaults`, you should hit your controller action with no error. Post your controller and the error then. – Wiktor Zychla Apr 09 '19 at 11:36
  • this link solved your problem: [Multiple Routes in MVC asp.net](https://stackoverflow.com/questions/16139743/registering-multiple-routes-in-mvc-asp-net) – hassan.ef Apr 09 '19 at 11:46

1 Answers1

1

You have to modify your code as below

  public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
          name: "Department",
          url: "{deptID}/{controller}/{action}",
          defaults: new { controller = "Department", action = "Index"}
      );

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


    }

Output

Home URL Department URL with ID

Let me know if the above code still not worked for you.

  • It doesnt give me an error now, but it calls the HomeController rather than the DepartmentController which i have set in the defaults object. – Michael Kirkegaard Apr 09 '19 at 11:58
  • It works. But it looks like i dont even need two routes. I can just use the main route and then make sure the default action doesnt require a departmentID parameter. – Michael Kirkegaard Apr 09 '19 at 12:43