I have a request model class that I'm trying to use the default Web API 2 model binding (.NET 4.6.1). Some of the query string parameters match the model properties, but some do not.
public async Task<IHttpActionResult> Get([FromUri]MyRequest request) {...}
Sample query string:
/api/endpoint?country=GB
Sample model property:
public class MyRequest
{
[JsonProperty("country")] // Did not work
[DataMember(Name = "country")] // Also did not work
public string CountryCode { get; set; }
// ... other properties
}
Is there a way to use attributes on my model (like you might use [JsonProperty("country")]
) to avoid implementing a custom model binding? Or is best approach just to use create a specific model for the QueryString to bind, and then use AutoMapper to customize for the differences?
Default Parameter Binding in ASP.NET Web API By default, if the parameter type is of the primitive type such as int, bool, double, string, GUID, DateTime, decimal, or any other type that can be converted from the string type then Web API Framework sets the action method parameter value from the query string.
Model Binding is the most powerful mechanism in Web API 2. It enables the response to receive data as per requester choice. i.e. it may be from the URL either form of Query String or Route data OR even from Request Body. It's just the requester has to decorate the action method with [FromUri] and [FromBody] as desired.
[FromQuery] - Gets values from the query string. [FromRoute] - Gets values from route data. [FromForm] - Gets values from posted form fields. [FromBody] - Gets values from the request body.
Using [FromUri] To force Web API to read a complex type from the URI, add the [FromUri] attribute to the parameter. The following example defines a GeoPoint type, along with a controller method that gets the GeoPoint from the URI.
Late answer but I bumped into this issue recently also. You could simply use the BindProperty
attribute:
public class MyRequest
{
[BindProperty(Name = "country")]
public string CountryCode { get; set; }
}
Tested on .NET Core 2.1 and 2.2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With