首页 文章

生成的UI文档不使用Swashbuckle AspNetCore来表达JsonProperty值

提问于
浏览
3

我创建了一个类,我想用它来发送排序和分页信息以应用于我的大型集合 . 我有一个.NET Core Web API服务,它将接收请求并将我的对象作为输入 FromQuery . 我想遵守某些参数名称的命名约定(即Microsoft Rest API Guidelines),例如 $orderby$top$skip 等,并使用 JsonProperty 注释了类的属性 .

但是,在生成的swagger doc中,这些只是显示为属性名称本身,如果我的属性名为 Take 但请求参数应为 $top ,则会出现问题 . 我希望生成的文档匹配,以免对API的消费者造成任何混淆 . 我读到的所有东西似乎都表明这应该有用,我很难过为什么它不适合我 .

这是我的 class 使用 Newtonsoft.Json.JsonPropertyAttribute 的注释

[JsonObject]
public class QueryParams {

    [JsonProperty( "$orderBy" )]
    public string OrderBy { get; set; }

    [JsonProperty( "$skip" )]
    public int? Skip { get; set; }

    [JsonProperty( "$top" )]
    public int? Take { get; set; }

    [JsonProperty( "$maxpagesize" )]
    public int? MaxPageSize { get; set; }

    [JsonProperty( "$count" )]
    public bool? IncludeCount { get; set; }
}

然后,例如我的Web API操作方法看起来像这样

[HttpGet( "type/{type}" )]
    public async Task<IActionResult> GetByType( 
        string type, 
        [FromQuery]QueryParams parameters ) 
    {
       /* ... */ 

    }

我已经尝试了几件事情,比如尝试使用 MapType ,如Override Schema for Specific Types所述,但是没有任何运气 . 欣赏任何人都可以提出的任何见解 .

1 回答

  • 3

    根据this GitHub issueJsonSerializer 不用于绑定到GET请求的类 . 您需要自定义模型绑定 .

    因此,当您使用类来表示查询参数时,不会涉及JsonSerializer . 相反,MVC模型绑定用于将请求中的值直接分配给实例属性 . 因此,如果您希望明确说明此行为所需的大小写,以及生成的描述,则还需要自定义模型绑定行为 . 我现在不是在我的笔记本电脑上,但是我认为你可以使用“FromQuery”注释属性并以这种方式设置绑定名称 .

    如果我正确理解GH问题中的讨论,以下内容应该有效:

    public class QueryParams {
    
        [FromQuery( Name = "$orderBy" )]
        public string OrderBy { get; set; }
    
        [FromQuery( Name = "$skip" )]
        public int? Skip { get; set; }
    
        [FromQuery( Name = "$top" )]
        public int? Take { get; set; }
    
        [FromQuery( Name = "$maxpagesize" )]
        public int? MaxPageSize { get; set; }
    
        [FromQuery( Name = "$count" )]
        public bool? IncludeCount { get; set; }
    }
    

相关问题