如何确定ASP.NET核心应用程序中的应用程序路由?

时间:2019-03-24 12:24:48

标签: c# asp.net-mvc asp.net-core asp.net-core-mvc

startup.cs文件中有下一个代码:

app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "catalog",
                template: "Catalog/{controller}/{action=Index}/{id?}");

            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

当我单击链接时:

 <a asp-controller="Products" asp-action="Index">Products</a>

应用程序使用名称为“ catalog”的路由,但是我需要名称为“ default”的路由。这该怎么做?请帮助。 对不起,我的英语不好=)

2 个答案:

答案 0 :(得分:0)

我建议稍微修改一下路由中间件:

您需要使用MapAreaRoute方法,该方法将告诉区域名称和URL格式。

app.UseMvc(routes =>
{
    routes.MapAreaRoute("catalog_route_name", "Catalog",
        "Catalog/{controller}/{action}/{id?}");

    routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
});

然后,您需要在控制器上指定Area属性。

namespace MyApp.Namespace1
{
    [Area("Catalog")]
    public class ProductsController : Controller
    {
        public IActionResult AddProduct()
        {
            return View();
        }        
    }
}

完成此更改后,您可以指定如下所示的区域:

    <a asp-area="Catalog" asp-controller="Products" asp-action="Index">
        Catalog/Products/Index
    </a>

这肯定可以工作。

答案 1 :(得分:0)

为使default生效,您可以更改顺序,例如

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
    routes.MapRoute(
        name: "catalog",
        template: "Catalog/{controller}/{action=Index}/{id?}");
});