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不支持它。
如果您确实需要支持不同的属性名称,您可以:
-
向
Actor
类添加其他属性作为别名。 -
创建自己的模型绑定器。
这是一个简单的模型绑定器:
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; } }
不要犹豫,评论我的代码:)
每个想法/评论都是受欢迎的。
上述就是C#学习教程:Web API表单 – urlencoded绑定到不同的属性名称分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1016910.html