Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using FromUri to bind object without parameter name prefixes

When using ASP.NET WebApi2 and Swashbuckle/Swagger, I am trying to bind an object using the FromUri attribute, something like this:

[RoutePrefix("api/v1/example")]
public class ExampleController : ApiController
{
    [HttpGet]
    [Route("{id}")]
    public ExampleModel Get(string id, [FromUri]ExampleModel searchCriteria)
    {
    ...
    }
}

public class ExampleModel
{
    public string id { get; set; }
    public string firstName { get; set; }
    public string lastName { get; set; }
}

I find that the URL to perform this GET operation and search by last name ends up being something like:

http://localhost:52259/api/v1/example/1?searchCriteria.firstName=paul

How can I remove the "searchCriteria" prefix from the query parameter? I want to keep it as an ExampleModel object in the controller's method signature, but be able to use (and have this reflected in the Swagger UI docs):

http://localhost:52259/api/v1/example/1?firstName=paul
like image 934
Paul K. Avatar asked Dec 09 '25 12:12

Paul K.


1 Answers

There's a Name property on the FromUri attribute. If I set that to an empty string, it makes the Swagger UI docs appear without the "searchCriteria." prefix:

public ExampleModel Get(string id, [FromUri(Name = "")]ExampleModel searchCriteria)
{
...
}

It appears that the controller receives the firstName regardless of whether or not there is a "searchCriteria." prefix as part of the query parameter name.

like image 89
Paul K. Avatar answered Dec 12 '25 02:12

Paul K.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!