【问题标题】:C# MVC HttpGet add parameters to routeC# MVC HttpGet 向路由添加参数
【发布时间】:2019-10-24 08:56:38
【问题描述】:

在我的控制器中,我有这样的操作:

    [Route("api/[controller]")]
    [ApiController]
    public class ManageOPIdentifierController : ControllerBase
    {
        [HttpGet("[action]")]
        public OPIdentifiersVM Get(int pageSize, int pageNumber)
        {

如何在HttpGet中添加参数pageSize和pageNumber?因为现在当我有第二个不带参数的方法 Get 时,我得到错误,因为有两个具有相同定义的路由。 第一个 HttpGet 路由应该怎么看?

[HttpGet("[action]/{pageSize}&{pageNumber}")]

上面的代码不起作用

编辑: 我的问题被误解了。 我有两种方法获取:

[HttpGet("[action]")]
public OPIdentifiersVM Get(int pageSize, int pageNumber)

[HttpGet("[action]")]
public List<OPIdentifierVM> Get()

从参数pageSize和pageNumber读取值没有问题。问题是我有两个具有相同 Http("[action]") 的方法。我得到错误:

AmbiguousMatchException: The request matched multiple endpoints. Matches: 
ManageUuidWeb.Controllers.ManageOPIdentifierController.Get (OneProjectIdentifier.Web)
ManageUuidWeb.Controllers.ManageOPIdentifierController.Get (OneProjectIdentifier.Web)

如果我很好地理解了评论,我必须更改其中一种方法的名称。但是我想知道是否可以有两个同名但参数不同的方法?

【问题讨论】:

标签: c# asp.net-mvc asp.net-web-api


【解决方案1】:
[HttpGet("[action]")]
public OPIdentifiersVM Get([FromUri] int pageSize, [FromUri] int pageNumber)

(或[FromRoute],如果您使用的是asp.net core)那么它将被访问

http://localhost/api/ManageOPIdentifier/Get/10/1

或为此使用查询参数(这将是更好的解决方案)

[HttpGet("[action]")]
public OPIdentifiersVM Get([FromQuery] int pageSize, [FromQuery] int pageNumber)

然后

http://localhost/api/ManageOPIdentifier/Get?pageSize=10&pageNumber=1

当您的操作名称等于 http 动词方法名称时,您也可以使用简单的[HttpGet]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 2020-02-19
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    相关资源
    最近更新 更多