【问题标题】:Custom routing in .NET Core 3 MVC.NET Core 3 MVC 中的自定义路由
【发布时间】:2020-04-17 21:53:45
【问题描述】:

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

如果网址如下所示:

 abc.com/tiger-animal

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

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

这意味着如果 url 包含最后一个字符串 -animal ,我想执行 AnimalController

我试过了

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

但它不起作用。

【问题讨论】:

  • 旁注:您不能执行控制器 - 您可以在控制器上执行方法(如Index 方法),但你不能像这样“执行”“整个”控制器......

标签: c# .net routing asp.net-core-3.0 .net-core-3.0


【解决方案1】:

去掉星号就可以了。
另外值得一提的是,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?}");
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    相关资源
    最近更新 更多