【问题标题】:How to pass 3 arguments to an Action? [duplicate]如何将 3 个参数传递给一个动作? [复制]
【发布时间】:2019-01-23 00:22:43
【问题描述】:

我正在尝试制作一个采用 3 个参数的 HTTP Get REST API。 但是,我收到错误或 3 个参数未通过。

我收到构建错误 - "HttpGetAttribute does not contain a constructor that takes 3 arguments"

这里是方法,我正在检查它。

https://localhost:44312/api/test/1/2/3

我已经删除了 HttpGet 行,但它没有帮助。

[Route("api/controller/{a}/{b}/{c}")]
[HttpGet("{a}", "{b}", "{c}")]
public string Get(int a, int b, int c){
  int sum = a + b + c;
  return sum.ToString();
}

我希望 URL 将这些参数传递给 REST GET API。

【问题讨论】:

  • 试过了,但是不行
  • 你在这里使用的网址 - 是我自己的网址
  • [HttpGet("{a}/{b}/{c}")]

标签: c# asp.net-core


【解决方案1】:

您需要对路由进行 2 处更改:

[Route("api/[controller]")]     // [controller]
[HttpGet("{a}/{b}/{c}")]        
public string Get(int a, int b, int c)
{
    int sum = a + b + c;
    return sum.ToString();
}

如果你想使参数成为必需的,那么你可以使用[Required]attribute

【讨论】:

  • “查看属性路由:ASP.NET Web API 2 中的属性路由”但问题是关于 ASP.NET Core,而不是 ASP.NET Web API 2,该链接是无用的。除此之外,你为什么要放置一个 Route 一个 HttpGet 属性? Route是给Controllers设置基础路由的,不是给Actions的
  • @CamiloTerevinto 您刚刚删除了 .asp.net-webapi 标签?在您编辑之前,问题和标题确实引用了 Asp.Net 核心 WebAPI 和 WebAPI 控制器。 OP 还声明他们正在制作一个 REST API。似乎符合我的解释。请解释一下?
  • 不,错了,我删除了 ASP.NET Core WebAPI 标签,因为问题中没有使用 ASP.NET Core Web API
  • 它有效,我如何将a,b,c作为必需参数?
  • @PrawnHongs 您可以尝试将[Required] 属性添加到每个参数([Required] int a)。另一种选择是创建一个带有[Required] 装饰属性的模型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-20
  • 2014-12-03
  • 2018-10-04
  • 2021-04-23
  • 1970-01-01
  • 2014-03-21
相关资源
最近更新 更多