Asp.Net core Swashbuckle set operationId

Александр Сысоев picture Александр Сысоев · Sep 10, 2018 · Viewed 8k times · Source

How can I set swagger operationId attribute in Asp.Net Core 2.1 project? According to this post I should use SwaggerOperationAttribute but I cannot find it in Swashbuckle.AspNetCore library. Also there is an IOperationFilter

  public interface IOperationFilter
  {
    void Apply(Operation operation, OperationFilterContext context);
  }

and I can't find any implementations for swagger generation purposes.

Answer

CoOl picture CoOl · Jan 21, 2019

There are 2 other options without having to write any extra code or add extra dependency like Swashbuckle.AspNetCore.Annotations

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 = "Test 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