gpt4 book ai didi

c# - 是否可以有多个仅因 ASP.NET Core 中的参数而异的 GET?

转载 作者:太空宇宙 更新时间:2023-11-03 14:38:40 25 4
gpt4 key购买 nike

我想构建真正的 RESTful 网络服务,所以不想利用 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)
{
}

而且我相信这会在 ASP.NET Web API 中起作用。但我遇到了一个异常(exception):

AmbiguousActionException: Multiple actions matched. The following actions matched route data and had all constraints satisfied:

TermsController.GetByParticipant (ParticipantTerms.Api)

TermsController.GetByProgram (ParticipantTerms.Api)

这两个属性都没有实际帮助:

  • [HttpGet]
  • [ActionName]
  • [FromQuery]

最佳答案

您可以使用 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)
{
}

关于c# - 是否可以有多个仅因 ASP.NET Core 中的参数而异的 GET?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58827875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com