gpt4 book ai didi

asp.net-mvc - 我如何同时绑定(bind) FromQuery 和 FromRoute 参数?

转载 作者:行者123 更新时间:2023-12-01 15:08:36 25 4
gpt4 key购买 nike

我需要同时支持基于查询参数的路由 (/api/models?id=1) 和基于路由的路由 (/api/models/1 >) 同时仍然允许明确访问模型集合 (/api/models)?

我的 Controller 看起来(有点)像这样:

[Route("/api/{controller}")]
public class ModelsController : Controller
{
[HttpGet]
public Models[] GetModels([FromQuery]QueryOptions queryOptions)
{
//...
}

[HttpGet("{id:int}")]
public Model Get([FromRoute] int id)
{
//...
}

[HttpGet("?{id:int}")]
public Model Get2Try1([FromQuery] int id)
{
//Fails with ": The literal section '?' is invalid.
//Literal sections cannot contain the '?' character."
//Which makes sense after some reading...
}

[HttpGet]
public Model Get2Try2([FromQuery] int id)
{
//Fails with "AmbiguousActionException: Multiple actions matched.
//The following actions matched route data and had all constraints satisfied:
//GetModels and Get2Try2"
//Which I think I understand as well...the absence of optional params
//means ambiguous routing...
}

[HttpGet] //What here?
public Model Get2Try3([FromQuery] int id) //and/or here?
{

}
}

我觉得应该有某种方法(通过声明式路由)来实现这一点。有没有人按照这些思路做过任何事情?

此外,当前代码库是 ASP.NET Core (RC1),不久将升级到 RTM/1.0。任何一方的细节可能相似,但我对任何一方/两者都感兴趣。

最佳答案

我发现以下方法有效:

[HttpGet, Route("{id?}")]

...关键是'?'。您不需要方法签名中的任何 [FromX],这可以解决问题并满足查询字符串和路由参数传递的需要。

不幸的是,Swagger UI 不喜欢它并期望一些显式参数开箱即用(https://github.com/domaindrivendev/Ahoy/issues/47https://github.com/domaindrivendev/Ahoy/issues/182),但这是另一回事了:)

关于asp.net-mvc - 我如何同时绑定(bind) FromQuery 和 FromRoute 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38731777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com