【问题标题】:.NET 6 Swagger guid generates "https://localhost:5001/api/sth/%7Bid%7D".NET 6 Swagger guid 生成“https://localhost:5001/api/sth/%7Bid%7D”
【发布时间】:2022-01-08 06:30:12
【问题描述】:

我对 Swagger 有意见。

当我尝试将查询作为参数传递时,它的 URL 格式不正确-> https://localhost:5001/api/sport/%7Bid%7D

预期的结果是这样的: https://localhost:5001/api/sport/00000000-0000-0000-0000-000000000001 调用时到达了我的端点。

我有这个路由参数,我的对象看起来像这样:

    [HttpGet("{id:guid}")]
    [ProducesResponseType(typeof(SportEventResource),(int)HttpStatusCode.OK)]
    [SwaggerOperation(
        Summary = "Gets a new Sport event",
        Description = "Gets a new Sport event with its associative Markets and Selections",
        OperationId = "sportEvent.get",
        Tags = new[] { "SportEventEndpoints" })]
    public async Task<ActionResult<SportEventResource>> Get([FromRoute]GetSportEvent query)
    {...
    // The parameter looks like this...
    public class GetSportEvent : IQuery<Sport>
    {
        public Guid Id { get; set; }
    }
   // The rest is basically the auto generated values.
   // Rest of Setup => Program.cs
   builder.Services.AddSwaggerGen(opt =>
   {
      opt.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
      opt.EnableAnnotations();
   });

   
   if (app.Environment.IsDevelopment())
   {
      app.UseSwagger();
      app.UseSwaggerUI();
   }

   

这是我的 Swagger 的生成方式: 每当我按下执行时,我都会收到一个未找到的错误,并且我的端点永远不会被调用。 查看网络选项卡,我可以看到格式错误的 url:https://localhost:5001/api/sport/%7Bid%7D

【问题讨论】:

  • 为什么你的方法参数是GetSportEvent 而不仅仅是Guid 本身?
  • 老实说只是在尝试......

标签: c# swagger guid .net-6.0


【解决方案1】:

%7Bid%7D url 解码为{id},这使得“有意义”,您要求一个具有 Id 属性的对象。这是一种 json 式的做法。

解决此问题的简单方法是删除您的类并直接绑定 Guid。

[HttpGet("{id:guid}")]
public async Task<ActionResult<SportEventResource>> Get([FromRoute] Guid id)
{

该参数需要称为id,因为这是您在模板中拥有的 ("{id:guid}")。

【讨论】:

  • 你在这里说的不是真的。当我直接从浏览器调用此端点时:https://localhost:5001/api/sport/00000000-0000-0000-0000-000000000001。有用。只有大摇大摆会导致问题。
  • 说实话,虽然你在这里说的是一种解决方法,但招摇喜欢......
【解决方案2】:

这似乎是由不匹配的字母大小写引起的 - URI 模板中的参数/api/sport/{id} 命名为id(小写),但方法参数命名为Id(大写“I”)。

尝试将public Guid Id 更改为public Guid id

[HttpGet("{id:guid}")] 更改为[HttpGet("{Id:guid}")]

【讨论】:

  • 你好,海伦,这行得通,谢谢。这有点丑。我更愿意只使用我猜的 Guid。
  • 我个人更喜欢 @gunr2171 的解决方案(即仅用 Guid 本身替换模型)。
猜你喜欢
  • 2017-11-10
  • 2014-07-03
  • 1970-01-01
  • 2019-12-23
  • 2019-06-17
  • 1970-01-01
  • 2015-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多