gpt4 book ai didi

c# - 简单的 ASP.NET Core 路由问题

转载 作者:行者123 更新时间:2023-11-30 23:01:46 24 4
gpt4 key购买 nike

使用以下内容

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

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

http://www.example.com/beacon 做了我期望的并点击了 BeaconController

但是 http://www.example.com/beacon/001 没有命中任何 Controller 并进入 404

我错过了什么?

最佳答案

您指定了路由模式 URL,但没有提到应该用什么 Controller /操作来处理这些类型的请求。

您可以在定义路由时指定默认选项

app.UseMvc(routes =>
{
routes.MapRoute(
name: "beacon",
template: "beacon/{id?}",
defaults: new { controller = "Beacon", action = "Index" }
);

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

假设您的Index 方法有一个id 可为空的int 类型的参数

public class BeaconController : Controller
{
public ActionResult Index(int? id)
{
if(id!=null)
{
return Content(id.Value.ToString());
}
return Content("Id missing");
}
}

另一种选择是从 UseMvc 方法中删除特定的路由定义,并使用属性路由来指定它。

public class BeaconController : Controller
{
[Route("Beacon/{id?}")]
public ActionResult Index(int? id)
{
if(id!=null)
{
return Content(id.Value.ToString());
}
return Content("Id missing");
}
}

http://www.example.com/beacon 之所以有效,是因为该请求结构与为默认路由定义的模式相匹配。

关于c# - 简单的 ASP.NET Core 路由问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50843312/

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