是否可以有多个仅因 ASP.NET Core 中的参数而异的 GET? [英] Is it possible to have multiple GETs that vary only by parameters in ASP.NET Core?
问题描述
我想构建真正的 RESTful Web 服务,所以不想利用 RPC 风格,所以现在有这个:
I want to build truly RESTful web service so don't want to leverage RPC-style, so have currently this:
[HttpGet]
[ActionName(nameof(GetByParticipant))]
public async Task<IActionResult> GetByParticipant([FromQuery]string participantId, [FromQuery]string participantType, [FromQuery]string programName)
{
}
[HttpGet]
[ActionName(nameof(GetByProgram))]
public async Task<IActionResult> GetByProgram([FromQuery]string programName)
{
}
而且我相信这会在 ASP.NET Web API 中工作.但我遇到了一个例外:
And I believe that would work in ASP.NET Web API. But I'm getting an exception:
AmbiguousActionException:匹配多个操作.以下操作与路线数据匹配并满足所有约束:
AmbiguousActionException: Multiple actions matched. The following actions matched route data and had all constraints satisfied:
TermsController.GetByParticipant (ParticipantTerms.Api)
TermsController.GetByParticipant (ParticipantTerms.Api)
TermsController.GetByProgram (ParticipantTerms.Api)
TermsController.GetByProgram (ParticipantTerms.Api)
这些属性都没有实际帮助:
Neither of the attributes actually help:
[HttpGet]
[ActionName]
[FromQuery]
推荐答案
当使用 from 查询时,你需要唯一区分动作的路由,否则你会得到模棱两可的动作异常.api/action?participantId=1&participantType=2
的原因与 api/action?programName=x
When using from query you need to uniquely differentiate the actions' routes otherwise you will get the ambiguous action exception. Reason being api/action?participantId=1&participantType=2
is the same as api/action?programName=x
建议:
public class ParticipantQuery {
public string participantId { get; set; }
public string participantType { get; set; }
public string programName { get; set; }
}
[Route("api/[controller]")]
public class TermsController : Controller {
[HttpGet("participants")] //GET api/terms/participants?participantId=123&....
[ActionName(nameof(GetByParticipant))]
public async Task<IActionResult> GetByParticipant([FromQuery]ParticipantQuery model) {
//...
}
[HttpGet("programs/{programName}")]//GET api/terms/programs/name
[ActionName(nameof(GetByProgram))]
public async Task<IActionResult> GetByProgram(string programName) {
//...
}
}
或者您可以使用一个动作来封装可用参数并根据提供的成员对结果进行分支
Or you can use one action that encapsulates the available parameters and branch the result based on the provided members
public class GetTermsQuery {
public string participantId { get; set; }
public string participantType { get; set; }
public string programName { get; set; }
}
[Route("api/[controller]")]
public class TermsController : Controller {
[HttpGet] //GET api/terms?participantId=123&....
public async Task<IActionResult> Get([FromQuery]GetTermsQuery model) {
//...
}
}
这篇关于是否可以有多个仅因 ASP.NET Core 中的参数而异的 GET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!