gpt4 book ai didi

c# - 如何为具有不同参数的同一Controller方法设置不同的路由?

转载 作者:太空宇宙 更新时间:2023-11-03 15:02:43 24 4
gpt4 key购买 nike

我的 ReportController 看起来像这样:

public IActionResult ReportDetails(int? reportId){
....
}

public IActionResult ReportDetails(int? reportId, bool ? approved) {
....
}

我尝试做一些路由,但失败了。在 Startup.cs 中编写的实际代码:

app.UseMvc(routes =>
{
routes.MapRoute(
name: "ReportDetailsValidation",
template: "descriptionValidation",
defaults: new { controller = "Report", action = "ReportDetails", reportId ="{reportId}", approved = "{approved}" }
);

routes.MapRoute(
name: "ReportDetails",
template: "description",
defaults: new { controller = "Report", action = "ReportDetails"}
);

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

如我所见,我需要匹配以下 URL:
/Report/ReportDetails?reportId=7 对于第一个和
/Report/ReportDetails?reportId=7&approved=True 第二个

最佳答案

你可以使用 RouteAttribute

[Route("ReportDetails/{reportId}")]
public IActionResult ReportDetails(int? reportId){
....
[Route("ReportDetails/{reportId}/{approved}")]
public IActionResult ReportDetails(int? reportId, bool ? approved) {
....

您的网址将是;

/Report/ReportDetails/7 为第一个和

/Report/ReportDetails/7/第二个为真

这将适用于默认的 startup.cs

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

关于c# - 如何为具有不同参数的同一Controller方法设置不同的路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45367992/

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