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?
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