Search code examples
c#asp.net-core-mvcasp.net-core-routing

Routing in c# ASP.NETcore


There is a problem with the Products/List string in _Layout. cshtml. When I launch the site and click on the Products tab, there is no redirection to the sheet section and it gives a 404 error.Instead of the address path specified in _Layout. cshtml (asp-action= "Products/List"), it outputs "Products%2FList". Is the problem related to the routing settings? However, if you enter the full address manually: https://localhost:44332/Products/List, then the controller finds it without any problems.

Layout:

    <ul class="navbar-nav flex-grow-1">
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
        </li>
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Products/List">Products</a>
        </li>

ProductsController :

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AppForPryaniki.Controllers
{
    public class ProductsController : Controller
    {
        private ProductReader reader;


        public ProductsController()
        {
            reader = new ProductReader();
        }

        // Products/List
        public IActionResult List()
        {
            List<Product> products = reader.ReadFromFile();

            return View(products);
        }

        // Products/Details/1
        public IActionResult Details(int id)
        {
            List<Product> products = reader.ReadFromFile();
            Product product = products.Where(x => x.Id == id).FirstOrDefault();

            if (product != null)
            {

                return View(product);
            }
            else
            {
                return NotFound();
            }
        }
    }
}

Settings routing:

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

HomeController

namespace AppForPryaniki.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {

            Product product = new Product();
            product.Id = 1;
            product.Name = "Test";

            return View(product);
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
        public IActionResult Products()
        {
            return View();
        }


        public IActionResult Test()
        {
            return View();
        }

    }
}

Solution

  • You have two mistakes here:

    <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Products/List">Products</a>
    

    Firstly, you are wanting to route to an action on your ProductsController, and so Home is the wrong value to use for asp-controller. Instead, you want to use Products.

    And secondly, the value for asp-action is also wrong, because the action you're wanting is called List, not Products/List. The correct value is List.

    Here is what it looks like after the changes:

    <a class="nav-link text-dark" asp-area="" asp-controller="Products" asp-action="List">Products</a>
    

    You were halfway to solving this on your own when you checked https://localhost:44332/Products/List to see if it worked. When you're able to navigate to something directly like that, it's always a sign the link you tried to generate in a view is where the problem lies.