使用 Web API 默认模型绑定器自定义属性名称?

Jas*_*n W 5 c# model-binding asp.net-web-api2 .net-4.6.1

我有一个请求模型类,我正在尝试使用默认的 Web API 2 模型绑定 (.NET 4.6.1)。一些查询字符串参数与模型属性匹配,但有些不匹配。

public async Task<IHttpActionResult> Get([FromUri]MyRequest request) {...}
Run Code Online (Sandbox Code Playgroud)

示例查询字符串:

/api/endpoint?country=GB
Run Code Online (Sandbox Code Playgroud)

示例模型属性:

public class MyRequest
{
    [JsonProperty("country")] // Did not work
    [DataMember(Name = "country")] // Also did not work
    public string CountryCode { get; set; }
    // ... other properties
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在我的模型上使用属性(就像您可能使用的那样[JsonProperty("country")])来避免实现自定义模型绑定?或者最好的方法只是使用为 QueryString 创建一个特定的模型来绑定,然后使用 AutoMapper 来定制差异?

And*_*ia 5

回答晚了,但我最近也遇到了这个问题。您可以简单地使用该BindProperty属性:

public class MyRequest
{
    [BindProperty(Name = "country")]
    public string CountryCode { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在 .NET Core 2.1 和 2.2 上测试