.NET 6 Swagger guid 生成 "https://localhost:5001/api/sth/%7Bid%7D"

.NET 6 Swagger guid generates "https://localhost:5001/api/sth/%7Bid%7D"

我对 Swagger 有疑问。

When I try to pass a query as a parameter it malforms the 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();
   }

   

Here is how my Swagger is generated: Whenever I press execute I get a not found error and my endpoint is never called. Looking at the network tab i can see the malformed url: https://localhost:5001/api/sport/%7Bid%7D

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

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

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

需要调用参数 id,因为这是模板中的内容 ("{id:guid}")。

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

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

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