NSwag MSBuild "The method 'get' on path '/api/Account' is registered multiple times"

Viewed 3981

I'm trying to generate a swagger specification with NSwag.MSbuild but when ever i do it throws me this message "The method 'get' on path '/api/Account' is registered multiple times"

Now the problem is that my methods are route less as shown bellow with some examples of the controller

        [HttpPost]
        [HttpGet]
        [AllowAnonymous]
        public IActionResult ExternalRegister(string provider, string returnUrl = null)

        [HttpGet]
        public IActionResult AddLogin(string provider, string returnUrl)

        [HttpGet]
        [AllowAnonymous]
        public ActionResult SignUpConfig()

I understand why it does this but what i don't understand is that doing the same thing in NSwag Studio works, the command i use is $(NSwagExe_Core22) webapi2swagger is there an option so that it generate succesfully like Nswag Studio ?

6 Answers

In a WebAPI if you have more than one HttpGet or HttpPost etc you should add Route Attribute to distinguish them.

Add HttpGet["{name}"]

Turns out you don't have to specify the routes if you don't want to it has something to do with the Default Url Template: /DefaultUrlTemplate:"{controller}/{action}/{id?}" adding {action} solved it for me

What helped me in this Situation was,to set the Route Attribute like this: [Route("SignUpConfig")] ,[Route("AdLogin")]

In my case, I had already added custom [Route("")] tags to all the paths. The problem was I had two public helper methods in the controller which NSwag identified as GET methods. Simply making them private (which they should have been anyway) made the problem go away...

In my case I had

[HttpGet, ActionName("Stuff")]
public async Task<Stuff> GetStuff(long byId, string color)
{
    /* Do things one way */
}

[HttpGet, ActionName("Stuff")]
public async Task<Stuff> GetStuff(string byName, string color)
{
    /* Do things another way */
}

The problem was that there were two identically named routes that take in different parameters. This is an overload situation that ASP.NET seems to be perfectly fine with but apparently blows NSwag's mind.

Because this was in legacy code, renaming the methods was not an option for me so I created a single method with optional parameters like so:

[HttpGet, ActionName("Stuff")]
public async Task<Stuff> GetStuff(string color, long? byId = null, string byName = null )
{
    if (byId != null)
    {
        /* Do things one way */
    }
    else
    {
       /* Do things another way */
    }
}

If your controller is decoreted with [Route("[controller]")]

then you need you specify seperate names

HttpGet("get1") and HttpGet("get2")

Else it will pick if decoration contains action name it it like

Route("[controller]/[action]") or from default route {controller}/{action}/{id?}

Related