Search code examples
c#asp.net-web-api2model-binding.net-4.6.1

Customize attribute names with Web API default model binder?


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?


Solution

  • 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