【问题标题】:Using FromUri to bind object without parameter name prefixes使用 FromUri 绑定没有参数名称前缀的对象
【发布时间】:2017-06-06 17:28:33
【问题描述】:

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

[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 对象保留在控制器的方法签名中,但能够使用(并将其反映在 Swagger UI 文档中):

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

【问题讨论】:

    标签: c# .net asp.net-web-api2 swagger swashbuckle


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-30
      • 1970-01-01
      • 2020-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多