Home > Mobile >  URL path is being repeated ASP.NET
URL path is being repeated ASP.NET

Time:02-28

I am in https://localhost:44311/ and I have those 2 buttons

enter image description here

When I press the Customers button I want to go to https://localhost:44311/Customers and see a list of the current Customers. Similarly https://localhost:44311/Movies and see a list of movies. For those two I have two Controllers, named MoviesController and CustomersController. This is my code in CustomersController:

 namespace MovieLab.Controllers
{
    public class CustomersController : Controller
    {
        public ActionResult AllCustomers()
        {
            var customers = new List<Customer>
            {
                new Customer(){ Name = "Customer 1"},
                new Customer(){ Name = "Customer 2" }
            };

            var customerViewModel = new CustomerViewModel()
            {
                Customers = customers
            };

            return View(customerViewModel);
        }
}

when I build the code above, my URL looks like this https://localhost:44311/Customers/AllCustomers shouldn't it be https://localhost:44311/AllCustomers? (I named it AllCustomers so the URL doesn't look like Customers/Customers)

CodePudding user response:

Your Default route in RouteConfig.cs looks like this:

url: "{controller}/{action}/{id}"

This will generate a url like:

https://localhost:44311/Customers/AllCustomers

Now to generate your required url, you need to set the route as (add it before the default one):

routes.MapRoute(
    name: "MyRoute",
    url: "allcustomers",
    defaults: new { controller= "Customers", action = "AllCustomers", id = UrlParameter.Optional }
);

// default route
routes.MapRoute("Default", "{controller}/{action}/{id}", new {controller = "Home", action = "Index", id = UrlParameter.Optional} );
  • Related