Home > Software engineering >  .NET 6 Swagger guid generates "https://localhost:5001/api/sth/{id}"
.NET 6 Swagger guid generates "https://localhost:5001/api/sth/{id}"

Time:12-02

I have an issue with Swagger.

When I try to pass a query as a parameter it malforms the URL-> https://localhost:5001/api/sport/{id}

The expected result is this one: https://localhost:5001/api/sport/00000000-0000-0000-0000-000000000001 Which when called reached my endpoint.

I have this route parameter and my object look like this:

    [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/{id}

enter image description here

CodePudding user response:

{id} url decodes to {id}, which makes ""sense"", you're asking for an object which has an Id property. That's a json-ish way of doing it.

Easy way to fix this is to remove your class and just bind the Guid directly.

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

The parameter needs to be called id because that's what you have in the template ("{id:guid}").

CodePudding user response:

This seems to be caused by mismatched letter case - the parameter in the URI template /api/sport/{id} is named id (lowercase) but the method parameter is named Id (uppercase "I").

Try either changing public Guid Id to public Guid id

OR

changing [HttpGet("{id:guid}")] to [HttpGet("{Id:guid}")].

  • Related