我宁愿有一个简单的 Controller ,其中只有 2 个这样的方法。
public class ColorsController : Controller
{
// GET: /<controller>/
public IActionResult Index()
{
return View();
}
public IActionResult Index(int id)
{
return View();
}
}
我在不同的命名空间中也有一个同名的 api。我尝试实现存储库模式,突然间我得到了 AmbigousActionException。我的 Web api 包含在 WebUI.controllers.api 命名空间中。 网络 API 是:
namespace ePress.WebUI.Controllers.api
{
[Route("api/[controller]")]
public class ColorsController : Controller
{
private IColorRepository _repository;
public ColorsController(IColorRepository colorRepository)
{
_repository = colorRepository;
}
// GET: api/values
[HttpGet]
public IActionResult Get()
{
return Ok(_repository.Get());
}
// GET api/values/5
[HttpGet("{id}")]
public IActionResult Get(int id)
{
var color = _repository.Get(id);
if (color != null)
return Ok(color);
return NotFound("Color not found");
}
}
这是Startup类中的路由配置:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
即使将主 Controller 的名称更改为 Colors2Controller,我仍然遇到相同的错误。 任何帮助将不胜感激。
最佳答案
我在一些非常基础的事情上费了好几个小时。 碰巧我的 Controller 中的 2 个 Action 都被评估为相同的。 所以我所要做的就是注释掉其中一种操作方法。
public class ColorsController : Controller
{
// GET: /<controller>/
public IActionResult Index()
{
return View();
}
//public IActionResult Index(int id)
//{
// return View();
//}
}
它现在解决了,这不是问题,因为 api 和我实现的存储库模式。 希望这对另一个人有帮助。
关于c# - 歧义操作异常 : Multiple actions matched in MVC Core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40828848/