Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 397
Jason W Avatar asked Jun 28 '18 16:06

Jason W


People also ask

Which of the following is a valid default rule for parameter binding in Web API?

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.

What is model binder in Web API?

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.

What is difference between FromQuery and FromBody?

[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.

What is the default attribute for passing complex data type to the Web API action?

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.


1 Answers

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

like image 60
Andrew Cachia Avatar answered Sep 18 '22 15:09

Andrew Cachia