Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.NET Core - Web Api - OpenApi Client method names

I'm generating my Swagger/OpenAPI descriptor in my API:

services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title = "AthCoin API",
                    Version = "v1",
                    Description = "Ath coin interop service.",
                    Contact = new OpenApiContact
                    {
                        Name = "Ricerca e Sviluppo",
                        Email = "[email protected]",
                        Url = new Uri("https://athena.srl/"),
                    },
                });
                
            });

... and in my client application (from Visual Studio) I'm generating automatically the client adding a "connected service".

On my API client each API method is mapped only using the action name:

  • UserController.Create() -> is mapped as SwaggerClient.Create()

  • ProductController.Create() -> is mapped ad SwaggerCient.Create2()

This is not useful. Is there is a way to change the autogenerated client, adding the controller's name in the generated method name?

For example:

  • UserController.Create() -> is mapped as SwaggerClient.UserCreate()
  • ProductController.Create() -> is mapped ad SwaggerCient.ProductCreate()
like image 945
Danilo Calzetta Avatar asked Oct 21 '25 00:10

Danilo Calzetta


2 Answers

Add nuget package Swashbuckle.AspNetCore.Annotations to your API project and mark your controller action with SwaggerOperationAttribute with OperationId parameter like this:

[SwaggerOperation(OperationId = "UserCreate")]
public async Task<IActionResult> Create()
{
    //whatever
    return Ok();
}

This will produce "operationId": "UserCreate" in the swagger JSON which in turn produces the desired UserCreate method in your generated client.

like image 51
Mirek Avatar answered Oct 23 '25 19:10

Mirek


This problem is discussed in this MS blog post. Basically all you need to do is include the name in the routing attribute. Depending on how your routing is set up that might look something like:

[HttpGet("/orders/{id}", Name = nameof(GetOrder))]
public async Task <ActionResult<Order>> GetOrder([FromRoute] Guid id)
{
    // ...
}
like image 45
Christopher Rhoads Avatar answered Oct 23 '25 18:10

Christopher Rhoads