【问题标题】:How to trigger ASP.NET Core API function when the parameter is included in URLURL中包含参数时如何触发ASP.NET Core API函数
【发布时间】:2021-06-05 01:08:40
【问题描述】:

我尝试在HeroesController类中触发特定方法(第二个):

    [HttpGet]
    public IEnumerable<Hero> Get()
    {
        return Heroes;
    }

    [HttpGet("/name={term}")]
    public IEnumerable<Hero> Get(string term)
    {
        return Heroes;
    }

调用此网址后:

https://localhost:44375/heroes/?name=Spider 

第一种方法被触发,而不是第二种。为什么呢?接收term参数的第二个如何触发?

【问题讨论】:

  • 因为路由不匹配,所以需要使用urlhttps://localhost:44375/heroes/name=Spider——但是在pattern中使用=是不常见的。
  • 是的,但我需要创建一个知道如何响应此特定 URL 的方法:localhost:44375/heroes/?name=Spider
  • 所以你已经有了第一个 Get 方法(正如你所说,它被调用了)。您想要的网址有一个名为query string 的部分。 Get 方法应该类似于 Get(string name)。第二个Get没有意义,去掉[HttpGet("/name={term}")]

标签: c# api asp.net-core postman httprequest


【解决方案1】:

正如 King King 在 cmets 中指出的那样,url 不匹配,但最好的方法是;

[HttpGet] 
public IEnumerable<Hero> Get([FromQuery] string term) 
{ 
    return Heroes; 
}

如果传递了查询参数termhttps://localhost:44375/heroes?term=Spider,则端点将被命中

【讨论】:

    【解决方案2】:

    这里有两点需要区分 - URL 参数与查询参数。如果您想在进行 GET HTTP 调用时提供变量,这些选项是:

    1. 您要传递的变量可以是 URL 的一部分:

      http://localhost:8080/yourResourceName/{varValue}

       [HttpGet]
       public Task<IActionResult> Get(string varValue)
       {
      
       }
      
    2. 你要传递的变量可以是查询参数:

      http://localhost:8080/yourResourceName?varname={varValue}

       [HttpGet]
       public Task<IActionResult> Get([FromQuery]string varValue)
       {
      
       }
      

    【讨论】:

      猜你喜欢
      • 2018-04-24
      • 2017-06-06
      • 2013-01-09
      • 1970-01-01
      • 2019-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-30
      相关资源
      最近更新 更多