1

I'm trying to create a code wrapper for an api with NSwag and Autorest.

Previously I was using Swashbuckle to generate the swagger file. It generated the swagger file with operationIds in the format actionMethod. This resulted in Autorest generating a code client that was 1-deep. All of the actions were on the top-level class.

For various reasons, I needed to change swagger generation to NSwag. This generates operationIds in the format controller_actionMethod. This results in AutoRest creating a composite class that exposes separate classes with actions for each controller.

How can either

  • Change how NSwag generates the operationIds
  • Change how Autorest maps operationIds

Note: I know I can manually change the swagger.json, but I'd like to keep a consistent automated process for generating the code client.

farlee2121
  • 2,959
  • 4
  • 29
  • 41

2 Answers2

5

There doesn't appear to be any readily available settings, but you can hook into the generation process of NSwag

https://github.com/RicoSuter/NSwag/wiki/Document-Processors-and-Operation-Processors#operation-processors

The operation processor

class FlattenOperationsProcessor: IOperationProcessor
{
    public async Task<bool> ProcessAsync(OperationProcessorContext context)
    {
        context.OperationDescription.Operation.OperationId = $"{context.MethodInfo.Name}";
        return true;
    }
}

Then add it in Startup.cs

document.OperationProcessors.Add(new FlattenOperationsProcessor());
farlee2121
  • 2,959
  • 4
  • 29
  • 41
  • exacly : services.AddOpenApiDocument(document => document.OperationProcessors.Add(new FlattenOperationsProcessor())) – Payedimaunt Dec 22 '21 at 14:14
0

Not sure if this was available when the question was asked, but here is a pretty easy way to do it:

services.AddSwaggerGen(c =>
{
    ...
    c.CustomOperationIds(d => d.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor ? controllerActionDescriptor.MethodInfo.Name : d.ActionDescriptor.AttributeRouteInfo?.Name);
});

The same can also be set via c.SwaggerGeneratorOptions.OperationIdSelector

Note that ActionDescriptor.AttributeRouteInfo?.Name is the default I used from the source code here

Adam
  • 1,580
  • 21
  • 40