gpt4 book ai didi

ASP.NET 核心路由不起作用

转载 作者:行者123 更新时间:2023-12-03 14:59:47 26 4
gpt4 key购买 nike

路由器是这样配置的:

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

我尝试请求的 Controller 操作如下所示:
//获取 api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value" + id;
}

当我请求时 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 传递到 Controller 操作?

最佳答案

我认为您需要指定 Controller 而不是 Action 。您的路线应定义为:

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

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

关于ASP.NET 核心路由不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39668039/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com