Reputation: 21
In a ASP.NET MVC application on .NET 4.8, I am using Swagger along with Swashbuckle to generate my API documentation. The automatic generation is working on some of the endpoint, not all of them.
For example when I have a endpoint like test(int id)
, the documentation get generated correctly. When I have parameter that are custom named, like test(int ids)
, nothing gets generated. Any idea why?
I tried various names for the parameter, but as soon as it's not id
, the doc don't get generated
Update:
Here is an example of a controller I am using (I fake the example to not provide real actual code):
public class FakeController : ApiController
{
/// <summary>
/// This is postint2
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public int Post(int id)
{
return 0;
}
/// <summary>
/// Post2
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
// GET: api/items/post2/{ids}
public int Post2(int ids)
{
return 0;
}
/// <summary>
/// This is postint2
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public int Post3(int id)
{
return 0;
}
}
My route looks like:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}/{action}",
defaults: new { id = RouteParameter.Optional, action = RouteParameter.Optional }
);
In this example, the endpoint Post2 documentation is not being generated. Probably because the parameter 'ids' does not match the default route I am using?
How could I generate the documentation for that Post2 without changing the behavior of the rest of the code? I do not want to change routes or affect in any way the endpoints since this code is already being heavily used in production.
Upvotes: 2
Views: 119
Reputation: 2909
Instead of changing your middleware/routing configuration, you simply need the Route attribute added to your controller methods, so that Swagger can correctly identify and parse them, like so...
public class FakeController : ApiController
{
/// <summary>
/// This is postint2
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public int Post(int id)
{
return 0;
}
/// <summary>
/// Post2
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
[Route("api/items/post2/{ids}")]
public int Post2(int ids)
{
return 0;
}
/// <summary>
/// This is postint2
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public int Post3(int id)
{
return 0;
}
}
Adding the [Route]
attribute to the Post2 method, you ensure that Swagger can correctly identify the route and generate the documentation. This way, you don't need to change the default routing configuration or affect the existing endpoints.
Upvotes: 0