简体   繁体   English

c# ASP.NETcore 中的路由

[英]Routing in c# ASP.NETcore

There is a problem with the Products/List string in _Layout. _Layout 中的 Products/List 字符串有问题。 cshtml. 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.当我启动站点并单击“产品”选项卡时,没有重定向到工作表部分,并给出 404 错误。而不是在 _Layout 中指定的地址路径。 cshtml (asp-action= "Products/List"), it outputs "Products%2FList". cshtml (asp-action="Products/List"),它输出"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.但是,如果您手动输入完整地址:https://localhost:44332/Products/List,则控制器会毫无问题地找到它。

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

    }
}

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 .首先,您想要路由到ProductsController上的操作,因此Home是用于asp-controller的错误值。 Instead, you want to use Products .相反,您想使用Products

And secondly, the value for asp-action is also wrong, because the action you're wanting is called List , not Products/List .其次, asp-action值也是错误的,因为您想要的操作称为List ,而不是Products/List The correct value is List .正确的值为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.当您检查https://localhost:44332/Products/List以查看它是否有效时,您已经自行解决了这个问题。 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.当您能够直接导航到类似的内容时,这始终表明您尝试在视图中生成的链接是问题所在。

The name of the Controller and Action are incorrect. Controller 和 Action 的名称不正确。 asp-controller should be Products and asp-action should be List . asp-controller应该是Products并且asp-action应该是List

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM