【问题标题】:.Net Core 3.1 API Routing not working as expected.Net Core 3.1 API 路由未按预期工作
【发布时间】:2020-10-06 11:43:56
【问题描述】:

我的 API 有一个相当简单的控制器。一种方法返回所有设备,另一种方法仅返回有关设备的信息。两者都是HttpGet。

我的路线定义:

[Route("api/device/list/{Id}")]
[ApiController]
public class DeviceController : ControllerBase

当我传入一个 ID 时,总是会调用这个方法:

[HttpGet]
public ActionResult<poiDevices> GetDeviceList()

PostMan URL 如下所示:

https://localhost:5001/api/device/list/mycoolid

当进行上述调用时,我希望它在下面调用此方法,使用 Id 参数定义:

    public ActionResult<DeviceDto> GetDeviceDetails(
    [FromRoute] string Id)

上面的代码有一个 Id 的占位符,所以我的期望是调用这个方法,而不是调用返回所有的泛型方法。如果我从 URL 中取出 Id,API 会返回 404 not found,这意味着我搞砸了这个路由部分。

我在这里错过了什么?

【问题讨论】:

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


    【解决方案1】:

    你应该像这样改变你的控制器。

    [Route("api/device")]
    [ApiController]
    public class DeviceController : ControllerBase
    {
    
      [HttpGet]
      [Route("list")]
      public ActionResult<poiDevices> GetDeviceList()  {
    
      }
    
      [Route("list/{id}")]
      public ActionResult<DeviceDto> GetDeviceDetails(
        [FromRoute] string Id)   {
    
      }
    
    }
    

    【讨论】:

    • 该死的,我就知道很简单......装饰方法......
    猜你喜欢
    • 2020-04-25
    • 2014-05-02
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 2013-01-13
    • 2016-08-19
    • 2015-09-09
    相关资源
    最近更新 更多