Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 478
Ole EH Dufour Avatar asked Apr 24 '26 11:04

Ole EH Dufour


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

like image 110
Adam Avatar answered Apr 27 '26 02:04

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!