7
votes

Les actions nécessitent une combinaison méthode / chemin unique pour Swagger

J'ai 2 méthodes HTTP GET dans le même contrôleur et me donne cette erreur

Méthode HTTP "GET" & chemin "api / DataStore" surchargée par les actions - DPK.HostApi.Controllers.DataStoreController.GetByIdAsync (DPK.HostApi), DPK.HostApi.Controllers.DataStoreController.GetAllAsync (DPK .HostApi) Les actions nécessitent une combinaison méthode / chemin unique pour Swagger 2.0.

Mon contrôleur:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info
            {
                Version = "v1",
                Title = " ",
                Description = " ",
                TermsOfService = "None",
                Contact = new Contact() { Name = " ", Email = " ", Url = " " }
            });
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();


        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        });
    }
}

Ma startup:

[Route("api/[controller]")]
[ApiController]
public class DataStoreController : ApiControllerBase
{
    private readonly IDataStoreService _dataStoreService;

    public DataStoreController(IDataStoreService dataStoreService)
    {
        _dataStoreService = dataStoreService;
    }


    [HttpPost]
    public async Task<IActionResult> PostAsync([FromBody] DataStoreCommand dataStoreCommand)
    {
        try
        {
            if (ModelState.IsValid)
            {
                await _dataStoreService.PostAsync(dataStoreCommand);
                return Ok();
            }

            var errorList = ModelState.Values.SelectMany(m => m.Errors).Select(e => e.ErrorMessage).ToList();
            return ValidationProblem();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }


    [HttpPut]
    public async Task<IActionResult> PutAsync([FromBody] DataStoreCommand dataStoreCommand)
    {
        try
        {
            if (ModelState.IsValid)
            {
                await _dataStoreService.PutAsync(dataStoreCommand);
                return Ok();
            }

            var errorList = ModelState.Values.SelectMany(m => m.Errors).Select(e => e.ErrorMessage).ToList();
            return ValidationProblem();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }


    [HttpDelete]
    public async Task<IActionResult> DeleteAsync(int id)
    {
        try
        {
            if (ModelState.IsValid)
            {
                var item = await _dataStoreService.GetByIdAsync(id);
                await _dataStoreService.DeleteAsync(item);
                return Ok();
            }

            var errorList = ModelState.Values.SelectMany(m => m.Errors).Select(e => e.ErrorMessage).ToList();
            return ValidationProblem();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }


    [HttpGet]
    public async Task<DataStoreQuery> GetByIdAsync(int id)
    {
        try
        {
            return await _dataStoreService.GetByIdAsync(id);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }





    [HttpGet]
    public async Task<IEnumerable<DataStoreQuery>> GetAllAsync(string instanceName, string dbname, string userName, string userPass, bool isActive, DateTime? startCreatedDate, DateTime? endCreatedDate, DateTime? startModifiedDate, DateTime? endModifiedDate)
    {
        object[] parameters = { instanceName, dbname, userName, userPass, isActive, startCreatedDate, endCreatedDate, startModifiedDate,  endModifiedDate};
        var parameterName = "@instanceName , @dbname , @userName , @userPass , @isActive , @startCreatedDate , @endCreatedDate , @startModifiedDate , @endModifiedDate";
        try
        {
            return await _dataStoreService.ExecWithStoreProcedure(parameterName, parameters);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }




}


0 commentaires

3 Réponses :


2
votes

vous devez mapper id dans HttpGet.

[HttpGet("{id}")]
public async Task<DataStoreQuery> GetByIdAsync(int id)
{
    try
    {
        return await _dataStoreService.GetByIdAsync(id);
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }
}

lorsque vous spécifiez HttpGet en ne fournissant pas de modèle, Swashbuckle essaie d'utiliser la valeur par défaut carte pour les deux. donc un conflit se produit.


0 commentaires

13
votes

Vous pouvez le résoudre comme suit:

[HttpGet("~/getsomething")]
[HttpGet("~/getothersomething")]

ou vous pouvez mettre des routes pour différencier vos méthodes, par exemple:

services.AddSwaggerGen (c =>
  {
    other configs;
    c.ResolveConflictingActions (apiDescriptions => apiDescriptions.First ());
  });
//in the Startup.cs class in the ConfigureServices method


1 commentaires

Santos La première solution signifierait que seule la première action est documentée dans Swagger. En règle générale, vous souhaitez éviter les points de terminaison non documentés ...



4
votes

J'ai changé la route du contrôleur comme suit:

[Route("GetById")]

ou vous pouvez également définir une route explicite pour l'action:

[Route("api/[controller]/[action]")]


0 commentaires