Asp.net core mvc 同一控制器中具有不同参数的多个端点
我已经好几年没有这样做了,我一定很热 我有我的家庭控制器:Asp.net core mvc 同一控制器中具有不同参数的多个端点,asp.net-core-mvc,url-routing,Asp.net Core Mvc,Url Routing,我已经好几年没有这样做了,我一定很热 我有我的家庭控制器: public ActionResult Index(string param1, string param2, string param3) { return View(); } public IActionResult Index() { return View(); } 我有一个Index.cshtml页面 在我的启动中,cs: ap
public ActionResult Index(string param1, string param2, string param3)
{
return View();
}
public IActionResult Index()
{
return View();
}
我有一个Index.cshtml页面
在我的启动中,cs:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}");
endpoints.MapControllerRoute(
name: "default2",
pattern: "{controller=Home}/{action=Index}/{param1}/{param2}/{param3}");
});
我得到的错误是:
**{“error”:“APP:请求与多个终结点匹配
public class HomeController : Controller
{
// hits when navigating to https://localhost:5001/one/two/three
[HttpGet("{param1}/{param2}/{param3}")]
public IActionResult Index(string param1, string param2, string param3)
{
return View();
}
// hits when navigating to https://localhost:5001/
public IActionResult Index()
{
return View();
}
}
在启动时#配置
我试过这个
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
namespace RouteTemplateProvider.Controllers
{
public class RouteWithParamAttribute : Attribute, IRouteTemplateProvider
{
public string Template => "{param1}/{param2}/{param3}";
public int? Order { get; set; }
public string Name { get; set; }
}
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[RouteWithParam]
public string Index(string param1, string param2, string param3)
{
return "Index with param";
}
public string Index()
{
return "Index no param";
}
}
}
谢谢,我试过了,但没有被调用。我设法找到了一种不同的方式来实现我想要的。我留下了这个问题,因为我很好奇是否有一个简单的解决方案。谢谢好的,请随时与社区分享你的解决方案。这是非常简单的东西,因此修复也应该很简单。是的,它应该是一个sim卡这是一个简单的解决方案,但我找不到。我自己的解决方案是不使用此方法并做其他事情。因此,为什么我没有回答我自己的问题,因为正如我之前所说,我做了其他事情。你似乎确信你自己的答案是正确的?我假设你测试了它?也许给出一个更完整的答案,以便我们社区能够验证你的答案?Tha当然可以,我会先用一个包含单个条目的标准配置替换app.UseEndpoints。我相信狗埋在了那个地方。我没有马上看到那个配置,对此表示抱歉。好主意:)我也这么认为,但我也在使用signalR,建议使用endpoints。另外,今天天气很热哈哈。我期待着你的答案。如果你解决了它,这可能是一个受欢迎的答案。祝你晚上愉快谢谢。还有你的时间。如果可以的话,我明天会测试。谢谢你:+1:)什么是:“公共整数?顺序=>2;"do?谢谢:+1关于Order属性:在这种情况下不需要它。这是设置路由顺序。顺序决定路由执行的顺序。首先尝试具有较低顺序值的路由。当路由未指定值时,它将获得默认值0。Order属性的空值表示用户未指定fy路由的显式顺序。我更新了代码。接受的答案与包含普通MVC控制器的问题有一点不同。接受的答案包含一个API控制器,其中两个方法都返回一个字符串,而不是IActionResult。
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
namespace RouteTemplateProvider.Controllers
{
public class RouteWithParamAttribute : Attribute, IRouteTemplateProvider
{
public string Template => "{param1}/{param2}/{param3}";
public int? Order { get; set; }
public string Name { get; set; }
}
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[RouteWithParam]
public string Index(string param1, string param2, string param3)
{
return "Index with param";
}
public string Index()
{
return "Index no param";
}
}
}