gpt4 book ai didi

c# - 使用 FromUri 绑定(bind)没有参数名称前缀的对象

转载 作者:行者123 更新时间:2023-12-03 18:47:11 28 4
gpt4 key购买 nike

在使用 ASP.NET WebApi2 和 Swashbuckle/Swagger 时,我尝试使用 FromUri 属性绑定(bind)对象,如下所示:

[RoutePrefix("api/v1/example")]
public class ExampleController : ApiController
{
[HttpGet]
[Route("{id}")]
public ExampleModel Get(string id, [FromUri]ExampleModel searchCriteria)
{
...
}
}

public class ExampleModel
{
public string id { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
}

我发现执行此 GET 操作并按姓氏搜索的 URL 最终类似于:

http://localhost:52259/api/v1/example/1?searchCriteria.firstName=paul

如何从查询参数中删除“searchCriteria”前缀?我想将它作为 ExampleModel 对象保留在 Controller 的方法签名中,但能够使用(并将其反射(reflect)在 Swagger UI 文档中):

http://localhost:52259/api/v1/example/1?firstName=paul

最佳答案

FromUri 属性上有一个 Name 属性。如果我将其设置为空字符串,它会使 Swagger UI 文档出现时没有“searchCriteria”。前缀:

public ExampleModel Get(string id, [FromUri(Name = "")]ExampleModel searchCriteria)
{
...
}

无论是否存在“searchCriteria”, Controller 似乎都会收到 firstName。前缀作为查询参数名称的一部分。

关于c# - 使用 FromUri 绑定(bind)没有参数名称前缀的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44396254/

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