zSynopsis
zSynopsis

Reputation: 4854

Asp.NET MVC Routing Issue: The resource can not be found

I have the following setup for my mvc web project

/Area
  Admin
    HomeController
  Customer
    HomeController
    YearController

/Controllers
  AgentsController
  EmployeeController

I would like to change a route for the Home Controller in the customer area to the following

http://mywebsite/Customer/{action}/{id}

I would also like all of the other routes to behave in the default manner. http://mywebsite/{area}/{controller}/{index}/{id} or http://mywebsite/{controller}/{index}/{id}

I went to my CustomerAreaRegistration and added the code below to the RegisterArea Method, but it's not working. When I navigate to http://mywebsite/Customer/Create or http://mywebsite/Agents/View, it displays the page correctly. But if I try to navigate to http://mywebsite/Customer/Year/Edit?yearId=3, it displays the resource can not be found.

Here's the register area method for my CustomerAreaRegistration

    public override void RegisterArea(AreaRegistrationContext context)
    {

        context.MapRouteLowercase(
           "MyCustomerHomeDefault",
           "Customer/{action}/{id}",
           new { controller = "Home", action = "Index", id = UrlParameter.Optional }
       );

        context.MapRouteLowercase(
          "Customer_default",
          "Customer/{controller}/{action}/{id}",
          new { action = "Index", id = UrlParameter.Optional }
        );
    }

I haven't made any other changes to my routing so I'm not sure what to do next. I downloaded the route debugger and its saying that the route that matches http://mywebsite/Customer/Year/Edit?yearId=3 is

Matched Route: Customer/{action}/{id}

Route Data
Key         Value
action      year 
id          edit 
area        Customer
controller  Home 

Can anyone please help me understand how I can fix this?

Upvotes: 0

Views: 92

Answers (1)

Karl Anderson
Karl Anderson

Reputation: 34846

Since routing entries are evaluated in the order they are entered into the registration, swap the route entries so that the more specific route is checked first and then the more general one second, like this:

public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRouteLowercase(
        "Customer_default",
        "Customer/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional }
    );

    context.MapRouteLowercase(
        "MyCustomerHomeDefault",
        "Customer/{action}/{id}",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

Upvotes: 2

Related Questions