In a WEB API controller, can we have the same method name with different HTTP Verbs?
[HttpGet]
public string Test()
{
return \"
The method names themselves don't matter to Swagger, the routes do. Swagger will blow up with that error when it detects potentially ambiguous routes. An ambiguous route being a single route (base uri) that returns more than 1 type of resource. For some crazy reason, Microsoft Web Api allows you to return different resources for the same URI and this is where you get into trouble with people trying to consume your API (and Swagger).
A single URI should represent a single resource.
Correct way:
Incorrect way:
Microsoft Web Api allows you to handle a single route with multiple methods and because of this you run a very serious risk of accidentally creating an ambiguous route.
Example of code that will break Swagger:
[HttpGet, Route("apples")]
public HttpResponseMessage GetApples()
{
return _productRepository.Get(id);
}
[HttpGet, Route("apples")]
pblic HttpResponseMessage GetApples([FromUri]string foo)
{
return new DumpTruck(); // Say WHAAAAAAT?!
}
A lot of Swagger frameworks scan your code at runtime and create a Swagger 2.0 JSON document. The Swagger UI requests that JSON document and builds the UI that you see based on that document.
Now because the Swagger framework is scanning your code to build the JSON, if it sees two methods that represent a single resource that return different types and it breaks. This happens because Swagger does not know how to represent that URI because it is ambiguous.
Here are some things you can do to help solve this problem:
If you HAVE to represent a single route with different types (typically a bad idea), then you can ignore routes that make the documentation ambiguous by adding the following attribute to the offending method
[ApiExplorerSettings(IgnoreApi = true)]
This will tell the documentation to ignore this method completely when documenting the API and Swagger will render. Remember that if you are using #2 then Swagger will NOT render this method which can cause problems for people consuming your APIs.
Hope this helps.