Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AspNetCore Custom/Explicit Swagger OperationId

I am creating restful APIs using aspnet core 2.2. I have a standard setup where each model has it's own controller with a GET and a POST actions. I am using Swashbuckle.AspNetCore NUGET package and using this article from Microsoft docs.

Now, when I look at the generated swagger file, it has multiple GET and POST operationIds. How can I configure custom operationIds without using Swashbuckle.AspNetCore.Annotations?

Here's what my Action methods look like:

[HttpPost]
[ProducesResponseType(200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public async Task<ActionResult<Response>> PostAsync([FromBody]Request request)
{
    Response result = await _context.PostAsync(request);
    return Ok(result);
}

I have multiple controllers, they're all following the same pattern.

My Startup class looks like this:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
    });

    ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseSwagger();

    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });

    ...
}

I have already looked at this solution, but don't want to go that route.

like image 577
CoOl Avatar asked Jan 27 '23 20:01

CoOl


1 Answers

After spending couple of hours trying to find the best solution, I found 2 approaches:

Option 1: Convention based - SwaggerGen has an option to set CustomOperationIds. So you can simply set it to use ControllerName_HttpMethod like this:

services.AddSwaggerGen(c =>
{
    c.CustomOperationIds(e => $"{e.ActionDescriptor.RouteValues["controller"]}_{e.HttpMethod}");
    c.SwaggerDoc("v1", new Info { Title = "ID&V API", Version = "v1" });
});

This will add operationIds to all your methods, following ControllerName_HttpMethod convention.

Option 2: ActionFilter/Attribute based - you can configure each Action method (as you'd do with SwaggerOperation action filter by simple adding a Name property to your HTTP verb action filter like this:

[HttpPost(Name="Post_Person")]
[ProducesResponseType(200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public async Task<ActionResult<Response>> PostAsync([FromBody]Request request)
{
    Response result = await _context.PostAsync(request);
    return Ok(result);
}

This works exactly like [SwaggerOperation(OperationId = "Post_Person")] but without the need of EnableAnnotations

Swashbuckle.AspNetCore documentation can be found here

like image 126
CoOl Avatar answered Jan 31 '23 09:01

CoOl