[SOLVED] URL path is being repeated ASP.NET

Issue

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)

Solution

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

Answered By – Rahul Sharma

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *