【问题标题】:Routing non-CRUD method to API Endpoint将非 CRUD 方法路由到 API 端点
【发布时间】:2022-01-13 14:43:58
【问题描述】:

请帮我完成我的家庭项目: 我可以毫无问题地调用所有 CRUD 方法,但我不知道如何将非 CRUD API 调用定向到正确的端点。

试过这个:

var rentalEvent = rest.GetSingle<RentalEvent>($"api/rentalevent/boo/{licensePlate}");

要达到这个目标:

[Route("/boo")]
[HttpGet("{licensePlate}")]
public RentalEvent GetGetRentalEventByLicensePlate(string licensePlate)
{
        return new RentalEvent { RenterId = 88 }; //mock return class
}

Controller类的属性设置为:

[Route("api/[controller]")] 
[ApiController]

【问题讨论】:

  • 尝试从操作中删除Route 属性,并改用[HttpGet("boo/{licensePlate}")]
  • 是的,我从没见过 Route 属性和 HttpGet 属性
  • 您正在使用控制器,一切都是请求/响应。端点应始终是相同的 URL。每个请求/响应都应该发送一个类对象,如
  • @Jonesopolis : Route 和 HttpGet 是允许的。请参阅:docs.microsoft.com/en-us/aspnet/web-api/overview/…
  • 我从未见过 Route 属性和 HttpGet 属性 - 我发现根本不使用 Route 非常方便。当有人说“/api/whatever/get/account/1”端点崩溃时,我可以按 Ctrl-F 输入 api/whatever/get/account 并进入处理方法。如果路由跨多个属性分解,尤其是如果其中一些属性隐藏在 [controller] 占位符中,那就更麻烦了

标签: c# api


【解决方案1】:

HttpGet 中指定的路由覆盖了您之前在Route 属性中设置的内容。尝试以下方法之一:

整个路由只使用HttpGet

[HttpGet("boo/{licensePlate}")]
public RentalEvent GetGetRentalEventByLicensePlate(string licensePlate)
{
        return new RentalEvent { RenterId = 88 }; //mock return class
}

或者使用不带参数的HttpGet 并将整个路由放在Route 属性中:

[Route("boo/{licensePlate}")]
[HttpGet]
public RentalEvent GetGetRentalEventByLicensePlate(string licensePlate)
{
        return new RentalEvent { RenterId = 88 }; //mock return class
}

有关详细信息,请参阅Attribute Routing in ASP.NET Web API

【讨论】:

  • 非常感谢。这解决了它!
【解决方案2】:

最好只在一个地方定义 Api 路由。

[HttpGet("/boo")]
public RentalEvent GetGetRentalEventByLicensePlate(string licensePlate)
{
        return new RentalEvent { RenterId = 88 }; //mock return class
}

对于 get 请求,通常应将字符串值用作查询中的可选参数。

api/rentalevent/boo?licensePlate=mylicense

在路由定义中放入任意字符串意味着不同的端点而不是不同的参数值。

【讨论】:

  • 非常感谢。这解决了它!很遗憾,我只能接受一个答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-23
  • 1970-01-01
  • 1970-01-01
  • 2016-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多