我想在浏览器/ api / announce和/ api / announce / 1中调用。 使用以下Get函数获取错误。当我注释掉其中一项或另一项工作时,但是如果我同时拥有这两项功能,则GET无法正常工作。签名有问题还是有其他问题?
/api/announce
[HttpGet]
public List<Announcement> GetAnnouncements()
{
Services.Interface.IAnnouncementService service = new Services.Imp.AnnouncementService(_configuration, _logger);
Announcements announcements = service.GetAnnouncements(1, 1);
return announcements;
}
/api/announce/1
[HttpGet]
public ActionResult<Announcement> GetAnnouncements([FromQuery]int ID)
{
Services.Interface.IAnnouncementService service = new Services.Imp.AnnouncementService(_configuration, _logger);
Announcement announcement = service.GetAnnouncement(ID);
return announcement;
}
答案 0 :(得分:1)
您的路由规则的签名相同,因此将引发此异常:Microsoft.AspNetCore.Mvc.Internal.AmbiguousActionException: Multiple actions matched.
要使框架了解您要调用的动作,您必须在路由方面更加具体。而且,如果要将参数作为路径的一部分传递,则必须将[FromQuery]
属性更改为[FromRoute]
属性。
示例:
[HttpGet]
public IActionResult Test()
{
return Ok();
}
[HttpGet("{id}")]
public IActionResult Test([FromRoute]int id)
{
return Ok();
}
答案 1 :(得分:0)
这就是我喜欢的方式:
[HttpGet]
[ProducesResponseType(typeof(IList<Currency>), 200)]
public async Task<IActionResult> GetAll()
{
return Ok(await _typeService.GetCurrenciesAsync().ConfigureAwait(false));
}
[HttpGet("{id}", Name = "GetCurrency")]
[ProducesResponseType(typeof(Currency), 200)]
public async Task<IActionResult> Get([FromRoute]int id)
{
return Ok(await _expenseService.GetCurrencyAsync(id).ConfigureAwait(false));
}
我们可以看到这样的东西:
/api/Currency
/api/Currency/{id}
您的基本控制器可能是这样的,其中包括基本路线:
[Authorize(Policy = Common.Security.Policies.ApiUser)]
[Route("api/[controller]")]
[Benchmark, ApiController]
public abstract class BaseController : ControllerBase
{
protected BaseController()
{ }
}
这里是完整性的控制器构造函数:
public class CurrencyController : BaseController
{
private readonly IExpenseEntryService _expenseService;
private readonly ITypeService _typeService;
public CurrencyController(ITypeService typeService, IExpenseEntryService expenseService)
{
_expenseService = expenseService;
_typeService = typeService;
}