繁体   English   中英

.NET Core 3 MVC 中的自定义路由

[英]Custom routing in .NET Core 3 MVC

你能帮我在 .NET Core 3 中创建自定义路由吗?

如果网址如下所示:

 abc.com/tiger-animal

然后我想在AnimalController上执行Index方法并将tiger作为查询字符串或Id参数传递。

当 url 看起来像这样: abc.com/aboutus ,路由应该执行Index? method on the aboutus 控制器Index? method on the与默认值一样。

这意味着我要执行AnimalController如果URL包含最后一个字符串为-animal

我试过了

  app.UseMvc(routes =>
            {
                routes.MapRoute("blog", "{*id}-animal",
                         defaults: new { controller = "animal", action = "index" });
                routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
            });

但它不起作用。

去掉星号,你应该没问题。
另外值得一提的是,ASP.NET Core 3.0 使用UseEndpoints而不是UseMvc ,因此配置路由的正确方法如下:

app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute("blog", "{id}-animal", new { controller = "animal", action = "index" });
        endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
    });

暂无
暂无

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

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