【问题标题】:Parameter Query is not working for API Get Method参数查询不适用于 API 获取方法
【发布时间】:2021-10-11 05:54:54
【问题描述】:

如果我用参数查询调用 HttpGet 方法,则只调用不带参数的 Get 方法。如何使用参数 id=2 调用第二个 Get 方法

http://localhost:10436/api/testapi?id=2

这里是代码

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

    namespace TestApi1
    {
        [Route("api/testapi")]
        [ApiController]
        public class TestApiController : ControllerBase
        {
            public ActionResult Get()
            {
                return Ok("Gets Working");
            }
    
            [HttpGet("{id:int}")]
            public ActionResult Get(int id)
            {
                return Ok("Gets Working with ID");
            }
        }
    }

【问题讨论】:

  • 您在 httpGet 中定义路由。所以这实际上是/api/testapi/Id?

标签: c# asp.net-mvc asp.net-core .net-core asp.net-core-webapi


【解决方案1】:

所有路由均使用 VS 2019 和 Postman 进行了测试。他们工作正常

如果你想使用

http://localhost:10436/api/testapi?id=2

改变你的行为

 public ActionResult GetById([FromQuery] int id)
{
   return Ok("Gets Working with ID");
}

但如果您想使用已有的操作,请使用此网址

http://localhost:10436/api/testapi/2

【讨论】:

  • 还是不行。 launchsetting.json 文件有问题吗。
  • @AlanPauil 您必须使用端点配置发布您的启动文件
【解决方案2】:
       [HttpGet("{id}")]
        public async Task<ActionResult> Get (int id)
        {
           //clarify code
        }

并发送此请求http://localhost:10436/api/testapi?id=2

您的代码可以工作。由于您的 id 大写和我认为的小写事实,您的代码不起作用。

更新

[HttpGet("idName/{id}")]

发送此请求http://localhost:10436/api/testapi/idName?id=2

另一个过程

   [HttpGet("{id}", Name = "Get")]
   public async Task<ActionResult> Get (int id)
        {
           //clarify code
        }


并发送此请求http://localhost:10436/api/testapi?id=2

另一个过程

   [HttpGet("{id}", Name = "GetById")]
   public async Task<ActionResult> GetById (int id)
        {
           //clarify code
        }


并发送此请求http://localhost:10436/api/testapi?id=2

【讨论】:

  • 不行,第一个Get方法是调用而不是调用第二个方法
  • @AlanPauil 我更新了我的答案。请检查。
  • @AlanPauil 我再次通过添加另一个进程更新了我的答案。它现在应该可以工作了。
  • @AlanPauil 我通过更改您的操作名称再次更新了我的答案,这将是我最后一次尝试。它现在应该可以工作了。请检查。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-20
  • 2020-05-31
  • 1970-01-01
  • 1970-01-01
  • 2018-07-19
  • 2012-08-30
相关资源
最近更新 更多