NSwagStudio, include Http request method name in client method names generated with NSwag

Viewed 815

I generate an Angular client for a.Net Core 3.1 API using NSwagStudio. The API includes endpoints that can be used with multiple Http request types (e.g. POST, GET). The client generates a method for each request with the same base name, plus a number.

The schema contains an endpoint /contract that supports GET and POST requests, and an endpoint /contract/{ID} that supports GET, POST and DELETE requests.

The generated client has methods like :

  • ContractAsync for GET requests without ID
  • Contract2Async for POST requests without ID
  • Contract3Async for GET requests with ID
  • Contract4Async for POST requests with ID
  • Contract5Async for DELETE requests with ID

I would like it to generate methods named:

  • GetContractAsync for GET requests without ID
  • PostContractAsync for POST requests without ID

etc

The answer to the question is to "implement and provide an own IOperationNameGenerator" See https://stackoverflow.com/a/49935417/4180382

I have no clue how to implement and provide this IOperationNameGenerator.

The "Web Api via reflection" tab contains several custom implementations but doesn't mention "IOperationNameGenerator"

How do I implement IOperationNameGenerator?

1 Answers

In your Startup.cs do this:

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

Related