aba*_*hev 8 c# .net-core asp.net-core asp.net-core-routing
我想构建真正的RESTful Web服务,所以不想利用RPC风格,所以目前有这样的:
[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)
{
}
Run Code Online (Sandbox Code Playgroud)
我相信这可以在ASP.NET Web API中使用.但我得到一个例外:
AmbiguousActionException:匹配多个动作.以下操作匹配路由数据并满足所有约束:
TermsController.GetByParticipant(ParticipantTerms.Api)
TermsController.GetByProgram(ParticipantTerms.Api)
这些属性都没有实际帮助:
[HttpGet][ActionName][FromQuery]And*_*ord 17
您可以使用IActionConstraint执行此操作.
这是一个例子:
public class ExactQueryParamAttribute : Attribute, IActionConstraint
{
private readonly string[] keys;
public ExactQueryParamAttribute(params string[] keys)
{
this.keys = keys;
}
public int Order => 0;
public bool Accept(ActionConstraintContext context)
{
var query = context.RouteContext.HttpContext.Request.Query;
return query.Count == keys.Length && keys.All(key => query.ContainsKey(key));
}
}
[HttpGet]
[ActionName(nameof(GetByParticipant))]
[ExactQueryParam("participantId", "participantType", "programName")]
public async Task<IActionResult> GetByParticipant([FromQuery]string participantId, [FromQuery]string participantType, [FromQuery]string programName)
{
}
[HttpGet]
[ActionName(nameof(GetByProgram))]
[ExactQueryParam("programName")]
public async Task<IActionResult> GetByProgram([FromQuery]string programName)
{
}
Run Code Online (Sandbox Code Playgroud)
从查询中使用时,您需要唯一地区分操作的路由,否则您将获得模糊操作异常.原因api/action?participantId=1&participantType=2是一样的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) {
//...
}
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用一个封装可用参数的操作,并根据提供的成员分支结果
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) {
//...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2879 次 |
| 最近记录: |