Web API表单 – urlencoded绑定到不同的属性名称

我期待一个内容类型设置为的POST请求:

内容类型:application / x-www-form-urlencoded

请求正文如下所示:

如first_name =约翰&姓氏=香蕉

我对控制器的操作有这个签名:

[HttpPost] public HttpResponseMessage Save(Actor actor) { .... } 

Actor类的给定位置为:

 public class Actor { public string FirstName {get;set;} public string LastName {get;set;} } 

有没有办法强制Web API绑定:

first_name => FirstName
last_name => LastName

我知道如何使用内容类型设置为application / json但不使用urlencoded的请求来执行此操作。

我98%肯定(我看过源代码)WebAPI不支持它。

如果您确实需要支持不同的属性名称,您可以:

  1. Actor类添加其他属性作为别名。

  2. 创建自己的模型绑定器。

这是一个简单的模型绑定器:

 public sealed class ActorDtoModelBinder : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { var actor = new Actor(); var firstNameValueResult = bindingContext.ValueProvider.GetValue(CreateFullPropertyName(bindingContext, "First_Name")); if(firstNameValueResult != null) { actor.FirstName = firstNameValueResult.AttemptedValue; } var lastNameValueResult = bindingContext.ValueProvider.GetValue(CreateFullPropertyName(bindingContext, "Last_Name")); if(lastNameValueResult != null) { actor.LastName = lastNameValueResult.AttemptedValue; } bindingContext.Model = actor; bindingContext.ValidationNode.ValidateAllProperties = true; return true; } private string CreateFullPropertyName(ModelBindingContext bindingContext, string propertyName) { if(string.IsNullOrEmpty(bindingContext.ModelName)) { return propertyName; } return bindingContext.ModelName + "." + propertyName; } } 

如果您正在迎接挑战,您可以尝试创建通用模型绑定器。

这是一个古老的post,但也许这可以帮助其他人。 这是一个带有AliasAttribute和相关ModelBinder的解决方案

它可以像这样使用:

 [ModelBinder(typeof(AliasBinder))] public class MyModel { [Alias("state")] public string Status { get; set; } } 

不要犹豫,评论我的代码:)

每个想法/评论都是受欢迎的。