【问题标题】:Swagger not defining parameters properlySwagger 没有正确定义参数
【发布时间】:2018-01-31 10:40:33
【问题描述】:

我正在使用 .netcore 创建一个简单的 REST API,并使用了 swashbuckle 包 (swashbuckle.aspnetcore\1.1.0),以便我可以轻松地对其进行开发测试。

配置服务:

services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info
            {
                Title = "Meetings Calculator API",
                Version = "v1",
                Description = "An API to provide pricing information related to journeys",
            });
        });

配置

app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1");
        });

一切都很好,除了我开发了一个电话后。看来我定义为在正文中传递的字典没有正确地提供给服务。

方法签名

[HttpPost("CalculateCost", Name = "CalculateCost")]
public IActionResult getJourneyCalculation([FromBody] IDictionary<String, String> locations)

生成的 json 配置

"parameters":[  
     {  
        "name":"locations",
        "in":"body",
        "required":false,
        "schema":{  
           "type":"object",
           "additionalProperties":{  
              "type":"string"
           }
        }
     }
  ],

我认为这就是字典应该存在的地方,所以我认为它的配置方面无法正常工作。有谁知道我需要做什么才能正确获取 IDictionary?

我遇到了一篇讨论此问题的帖子,其中指出拼写存在错误(或至少不一致)导致字符串中出现问题“s”v“S”,但我都尝试过,没有任何变化。我认为这也很旧并被引用为固定的。我还尝试了一些更改 UseSwaggerUI 端点的建议,但对我所做的只是让我看到一个空白屏幕。

[更新] 我似乎只从字典中得到一个条目,例如,如果我使用输入:

{
    "2":"London",
    "2":"Bristol",
    "2":"London",
    "2":"Newcastle"
}

最后一个条目将进入控制器。

[更新] 我已经尝试过了,它会间歇性地工作:

 with arguments ([""]) - ModelState is Invalid

 with arguments (["System.Collections.Generic.Dictionary`2[System.String,System.Int32]"]) - ModelState is Valid

使用相同的输入:

{
    "London":2,
    "Bristol:2",
    "London:2",
    "Newcastle":2
}

间歇性有点像索赔,因为它工作了两次,之后就没有了。

【问题讨论】:

    标签: .net-core swagger swagger-ui


    【解决方案1】:

    好的,我通过定义自己的类来保存这两个值来找到解决方法。

    public class FromLocation
    {
        [Required]
        public string Location { get; set; }
        [Required]
        public int Attendees { get; set; }
    }
    

    将控制器签名更改为:

     public IActionResult getJourneyCalculation([FromBody] IList<FromLocation> locations)
    

    现在黄色模式框列出了类型,我可以根据需要发送信息。不知道字典是怎么回事,但生命太短了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-30
      • 2011-04-17
      • 2013-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多