c# - Swagger 显示错误的查询参数

标签 c# asp.net-core swagger

我有这个 Controller 和操作方法:

[ApiController]
[Route("api/[controller]")]
public class AppointmentController : ControllerBase
{        
    [Route("{provider}/AvailableSlots")]
    [HttpGet]        
    public Task<AvailableSlotsResponse> GetAvailableSlots(Request<AvailableSlotsRequest> request)
    {
        return null;
    }
}

这是模型:

    public class Request<T> where T : class
    {
        [FromRoute]
        public string Provider { get; set; }
        [FromQuery(Name = "")]
        public T Model { get; set; }
    }

    public class AvailableSlotsRequest
    {
        //[FromQuery(Name = "Location")] //Would prefer not to have to use this
        public string Location { get; set; }
    }

我需要使用 Location 作为 URL 中的查询参数名称,以便按预期命中端点。

例如。 http://localhost/api/Appointment/Company/AvailableSlots?Location=SYD

但是,当我查看 Swagger 页面时,该参数名为 Model.Location,这让 API 的使用者感到困惑:

swagger

我可以使用 [FromQuery(Name = "Location")] 强制 Swagger 显示 Location,但这感觉非常多余,并且会重复属性名称。

这是我在 ConfigureServices() 中设置的 Swagger:

services.AddSwaggerDocument(document =>
            {
                document.PostProcess = d =>
                {
                    d.Info.Version = Configuration["APIVersion"];
                    d.Info.Title = $"{Configuration["ApplicationName"]} {Configuration["DomainName"]} API";
                };
            });

如何让 Swagger 显示 Location 而不是 Model.Location,而不必在 [FromQuery] 中重复“Location”一词> 属性?

最佳答案

向 Controller 参数添加属性[FromRoute]:

    public Task<AvailableSlotsResponse> GetAvailableSlots([FromRoute]Request<AvailableSlotsRequest> request)

删除 Model 属性中的属性 FromQuery,并取消 Location 属性中属性 FromQuery 的注释。

enter image description here

关于c# - Swagger 显示错误的查询参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55588075/

相关文章:

c# - 将窗口解除 Hook 到其原始状态

c# - 将 VB 转换为 C# FileSystem.Dir 后

c# - EF : The instance of entity type X cannot be tracked because another instance of this type with the same key is already being tracked

javascript - ASP NET Core - 以编程方式清除 ResponseCache

python - 如何测试 Connexion/Flask 应用程序?

spring-boot - Spring Boot OpenAPI 3 - 如何传递分页详细信息?

java - 开放API 3.0.1只读注解

c# - Rider "extern alias"和 "using"支持

c# - 在 EF Core 中按孙子属性过滤父集合

c# - 用于构建加载我的程序集并构建序列化 NHibernate 配置的 MSBuild 任务