Skip to main content
 首页 » 编程设计

c#之使用 Web API 默认模型 Binder 自定义属性名称

2024年02月25日36lexus

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

public async Task<IHttpActionResult> Get([FromUri]MyRequest request) {...} 

示例查询字符串:

/api/endpoint?country=GB 

示例模型属性:

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

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

请您参考如下方法:

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

public class MyRequest 
{ 
    [BindProperty(Name = "country")] 
    public string CountryCode { get; set; } 
} 

在 .NET Core 2.1 和 2.2 上测试