c# - Asp.net 核心路由 ambiguousActionException
问题描述
我有 2 controllers
,我收到错误:
> AmbiguousActionException: Multiple actions matched. The following
> actions matched route data and had all constraints satisfied:
> WebApi.Controllers.BlacklistController.GetBlacklists (WebApi)
> WebApi.Controllers.WhitelistController.GetWhitelists (WebApi)
这是我的控制器
[Produces("application/json")]
[Route("api/infrastructure/blacklist")]
public sealed class BlacklistController : Controller
{
private readonly IInfrastructure _infrastructure;
public BlacklistController(IInfrastructure infrastucture) => _infrastructure = infrastucture;
[HttpGet]
[Route("/")]
public async Task<IEnumerable<BlacklistedAgent>> GetBlacklists() => await _infrastructure.GetBlacklistedAgents().ConfigureAwait(false);
}
WhitelistController.cs:
[Produces("application/json")]
[Route("api/infrastructure/whitelist")]
public sealed class WhitelistController : Controller
{
private readonly IInfrastructure _infrastructure;
public WhitelistController(IInfrastructure infrastructure) => _infrastructure = infrastructure;
[HttpGet]
[Route("/")]
public async Task<IEnumerable<WhitelistRequest>> GetWhitelists() => await _infrastructure.GetPendingWhitelistRequests().ConfigureAwait(false);
[HttpPost]
[Route("/")]
public async Task<ActionResult<WhiteListingResponse>> RequestWhitelisting(Guid agentId, string fqdn)
{
var result = await _infrastructure.RequestWhitelistingForAgent(agentId, fqdn).ConfigureAwait(false);
switch (result)
{
case WhiteListingResponse.Blacklisted:
return Forbid();
case WhiteListingResponse.SuccessfullyAddedToAwaitingWhitelist:
return Ok();
case WhiteListingResponse.ConflictStopsAddingToAwaitingWhitelist:
{
await _infrastructure.CreateUnresolvedIdentity(agentId, fqdn).ConfigureAwait(false);
return Conflict();
}
default:
return BadRequest();
}
}
}
为什么不是disambiguating
基于Route attribute
控制器上的方法?
解决方案
应用于以 / 开头的操作的路由模板不会与应用于控制器的路由模板组合。
[Route("Home")]
public class HomeController : Controller
{
[Route("")] // Combines to define the route template "Home"
[Route("Index")] // Combines to define the route template "Home/Index"
[Route("/")] // Doesn't combine, defines the route template ""
public IActionResult Index()
{
ViewData["Message"] = "Home index";
var url = Url.Action("Index", "Home");
ViewData["Message"] = "Home index" + "var url = Url.Action; = " + url;
return View();
}
[Route("About")] // Combines to define the route template "Home/About"
public IActionResult About()
{
return View();
}
}
这是设计使然,并在此处记录。
推荐阅读
- javascript - 为什么 YouTube IFRAME Player API 不加载下一个视频?
- php - 如何将某个位置的数组插入另一个数组?
- python - 使用 Keras 回调更改数据集
- mysql - 将数据库时间戳与当前时间进行比较
- angular - 不允许通过字符串文字访问对象!当我尝试通过动态 id 访问 (route.params['id'] 路由参数时
- kubernetes - 如何识别 pod eviction 策略?
- c++ - 错误与“operator=”不匹配(操作数类型为“Person”和“Person*”)
- unix - vim 可以在不将换行符(^@)字符视为“Enter”键的情况下回显寄存器的内容吗?
- android - 如何设置 WhatsApp 聊天等表情符号,而不是特定于移动设备
- node.js - fs.writeFile 客户端尝试获取文件时