I have integrated swagger in WebApi 2 application. It works fine when application has single controller. When I added second controller in the application. I got following
Add route attribute for the method [Route("ApiAnotherFunction")]
and [HttpGet]
.
The problem can also occur in a situation where you use attribute routing.
If the attribute route conflicts with a routingtable route you will have the 'multiple operations' error.
Example:
[HttpGet]
[SwaggerOperation("GetByUsername")]
[Route("[path]/User")]
public IHttpActionResult GetUser(string username)
{
}
more info on attribute routing: https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
In the file AppStart/SwaggerConfig.cs
First one, you must import Linq
using System.Linq;
And add in the same file, this line
c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
just inside of:
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{ ...
One consideration:
In your controllers, you must use the Http methods
:
[HttpGet]
[Route("something")]
public List<model> something(){....}
[HttpGet]
[Route("something2")]
public List<model2> something2(){....}
[HttpPost]
[Route("mypost1")]
public List<model> mypost1(){....}
[HttpPost]
[Route("mypost2")]
public List<model2> mypost2(){....}
An answer I haven't seen: I bungled up usings.
My controller has some MVC items (List items) and thus has a link:
using System.Web.Http;
using System.Web.Mvc;
Because of this, somehow, it got registered twice (I assume). Problem was fixed by using the full qualification for RoutePrefix/Route/HttpGet and others.
namespace MyNameSpace
{
[System.Web.Http.RoutePrefix("api/Reports")]
public class ReportsController
{
{...constructor...}
[System.Web.Http.Route("Scans")]
[System.Web.Http.HttpGet,ResponseType(typeof(List<ReportClass>))]
public ascyn Task<HttpResponseMessage> GetScans() {...}
You have two options for the above two methods:
Combine two methods into single one with three parameters - each one will be in the query string
Have separate route urls like - api/controller/byusername
and api/controller/bycredentials
You can change the route on your controller.
The default value is [Route("api/[controller]")]
You can change to [Route("api/[controller]/[action]")]