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

标签 c# asp.net-core .net-core asp.net-core-routing

我想构建真正的 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/

相关文章:

asp.net-mvc - MVC 6 应用程序在 View 加载后不释放内存

c# - 为什么 HttpClientHandler 没有正确获取和使用默认代理设置?

.net-core - 为什么新的 .Net Core 项目不允许我在 VS2017 15.4.3 中选择 Core Framework?

c# - 您将如何使用 LINQ 编写此映射过滤器链?

c# - 在 C# 中使用 new 关键字继承

c# - 如何在 C# 中使用多个列表选择检查 null 条件?

c# - 适用于 .NET 核心的 IronPython

c# - 在 LINQ 中集成 NULL 检查

C# : Prevent child modal form from creating instance on taskbar

c# - Microsoft Graph - GraphServiceClient 使用另一个帐户阅读电子邮件