Bind parameters from query and form at the same time in ASP.NET

Viewed 83

I'm working on an ASP.NET Web API with the following class parameter example:

using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;

public class DetailsParameters
{
    [SwaggerParameter("NameParameterDescription")]
    [FromQuery(Name = "name")]
    public string Name { get; set; }

    [SwaggerParameter("DescriptionParameterDescription")]
    [FromQuery(Name = "description")]
    public string Description { get; set; }

    // And many more . . .
}

Then I use it in my controller:

public class DetailsController : ControllerBase
{
    [HttpGet]
    public IActionResult GetDetails([FromQuery] DetailsParameters detailsParameters)
    {
        // Some code here, work with the params inside detailsParameters variable
    }
}

But now I want to add a POST method that should use the exact same thing - same parameters with same swagger descriptions. The difference I need is those parameters to be taken as form parameters, not as query params.

The method in the controller should look like this:

public IActionResult AddDetails([FromForm] DetailsParameters detailsParameters)
{
    // do something with those parameters
}

But they are still query parameters in the parameters object. I tried to modify the properties and added FromForm attribute:

[SwaggerParameter("NameParameterDescription")]
[FromQuery(Name = "name")]
[FromForm(Name = "name")]
public string Name { get; set; }

Unfortunately, it does not work as I wanted. A workaround would be to create a new class with all the same properties and description but with different binding attributes.

Still, I believe there should be a better way to resolve this. Any ideas?

0 Answers
Related