是否可以有多个仅因ASP.NET Core中的参数而异的GET? [英] Is it possible to have multiple GETs that vary only by parameters in ASP.NET Core?

查看:181
本文介绍了是否可以有多个仅因ASP.NET Core中的参数而异的GET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

您可以使用IActionConstraint来做到这一点。

You can do this using an 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)
{
}

这篇关于是否可以有多个仅因ASP.NET Core中的参数而异的GET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆