Web API: same method with different HTTP verbs

In the WEB API controller, can we have the same method name with different HTTP verbs?

  [HttpGet]
        public string Test()
        {
            return "Success Get";
        }


  [HttpPost]
        public string Test(int i)
        {
            return "Success Post";
        }

Swagger does not accept this configuration. I get this error when accessing API methods:

500: "Message": "An error occurred.", "ExceptionMessage": "Swagger 2.0 is not supported: several operations with the" api / Common "path and the" POST "method. See configuration settings - \" ResolveConflictingActions \ "for a potential workaround ways "

Here is mine routeconfig:

  config.Routes.MapHttpRoute(
                name: "DefaultApiByName",
                routeTemplate: "api/{controller}/{action}/{name}",
                 defaults: new { id = RouteParameter.Optional }
                );

            config.Routes.MapHttpRoute(
                name: "DefaultApiByAction",
                routeTemplate: "api/{controller}/{action}"
                );

            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id=RouteParameter.Optional});
+3
source share
4 answers

Swagger, . Swagger , . - ( uri), 1 . - Microsoft Web Api URI, , API ( Swagger).

URI .
:

  • GET/apples//
  • GET/apples? type = red//

:

  • GET/apples///
  • GET/apples? type = red//

Microsoft Web Api , - .

, 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?!
}

Swagger JAON Swagger 2.0. Swagger , JSON , .
, Swagger JSON, , , , . , Swagger , URI, .

, :

  • , ( URI) .
  • ( , ), , ,

    [ApiExplorerSettings (IgnoreApi = true)]

, API Swagger . , # 2, Swagger , , API.

, .

+9

.

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

. .

[Route("api/Test")]
[Route("api/Test/{id}")]
+2

:

config.Routes.MapHttpRoute(
         name: "DefaultApi",
         routeTemplate: "api/{controller}/{id}",
         defaults: new { id = RouteParameter.Optional }
    );

And write the following code:

config.Routes.MapHttpRoute("DefaultApiWithAction", "api/{controller}/{action}");
0
source

Add a separate route to your conflicting methods. For example, [Route("GetByType")]above one and the [Route("GetById")]other.

OR, for ASP.NET Core, when downloading the file for swagger, add the following configuration:

 services.AddSwaggerGen(options =>
            {
                options.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
}
0
source

Source: https://habr.com/ru/post/1655238/


All Articles