2

I just added swagger to my api to generate some documentation...

normally, my front end code would do a "get by id" like this:

https://whatever.com/api/GetDisplayContainer/A90555CD-931E-4D9D-D51D-08D63E83FCC6

however, swaggers "try it" wants to send:

https://whatever.com/api/GetDisplayContainer?id=A90555CD-931E-4D9D-D51D-08D63E83FCC6

I want to be able to support both ways. How do I do it?

Here is an example of a controller method:

[HttpGet]
[Route("GetDisplayContainer")]
public ApiResponse<ContainerDisplayViewModel> GetDisplayContainer(Guid id)
{
    return ApiResponse.Convert(ResourceService, _containerService.GetDisplayContainerById(id));
}

I don't really want to have to change my existing code to do it the "query string" way. because its a totally valid way of doing it. But it would be nice to be able to support both...

This is C# using .net core 2.1.

Thanks!

4
  • 1
    If you had your route set as "GetDisplayContainer/{id}" then swagger would probably suggest the format you want Commented Nov 26, 2018 at 17:24
  • this works - thanks! if u suggest it as an answer, i will mark it as accepted.. Commented Nov 27, 2018 at 10:12
  • What happened to the 500 error? Commented Nov 27, 2018 at 10:22
  • 1
    i realised it was caused by there not being a valid session, once i logged in it worked as expected through the swagger ui, so it was a red herring... Commented Nov 27, 2018 at 12:33

2 Answers 2

2

You can do two routes:

[HttpGet]
[Route("GetDisplayContainer")]
public ApiResponse<ContainerDisplayViewModel> GetDisplayContainer([FromQuery] Guid id)
{
}

and

[HttpGet]
[Route("GetDisplayContainer/{id}")]
public ApiResponse<ContainerDisplayViewModel> GetDisplayContainerRoute([FromRoute] Guid id)
{
}
Sign up to request clarification or add additional context in comments.

2 Comments

so the only way is to have a duplicate of every get method that takes a parameter? that seems kind of bad...
Yes, it's not ideal if you have to do more than one route. I'm glad the other solution worked!
1

If you change your route from GetDisplayContainer to GetDisplayContainer/{id} then Swagger will know that the parameter is not located in the query string and should generate your desired output.

Full code:

[HttpGet]
[Route("GetDisplayContainer/{id}")]
public ApiResponse<ContainerDisplayViewModel> GetDisplayContainer(Guid id)
{
    return ApiResponse.Convert(ResourceService, _containerService.GetDisplayContainerById(id));
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.