ASP.NET 核心路由不起作用

blg*_*boy 7 asp.net asp.net-core-mvc

路由器是这样配置的:

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

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "spa-fallback",
        template: "{*url}",
        defaults: new { controller = "Home", action = "Index"});
});
Run Code Online (Sandbox Code Playgroud)

我尝试请求的控制器操作如下所示:// GET api/values/5

[HttpGet("{id}")]
public string Get(int id)
{
    return "value" + id;
}
Run Code Online (Sandbox Code Playgroud)

当我请求http://localhost:54057/api/values/get 时,我得到“value0”。

当我请求http://localhost:54057/api/values/get 时,我得到“value0”。

当我请求http://localhost:54057/api/values/get/5 时,我得到一个 404 Not Found。

我的路由配置是否不正确,或者为什么“id”参数没有从 URL 传递到控制器操作?

Hus*_*vic 1

我认为您需要指定控制器而不是操作。您的路线应定义为:

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "api",
        template: "api/{controller}/{id?}"); <-- Note the change here
});

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "spa-fallback",
        template: "{*url}",
        defaults: new { controller = "Home", action = "Index"});
});
Run Code Online (Sandbox Code Playgroud)

在未指定参数时获得结果的原因很可能是由于调用了后备路由。如果您想知道正在调用哪个路由,请查看这篇关于路由调试的文章。

  • 该调试包似乎不适用于核心 (3认同)
  • 您可以将 MapRoute() 放在第一个 UseMvc() 中。 (2认同)