网页API的形式,urlen codeD绑定到不同的属性名称 [英] Web API form-urlencoded binding to different property names
问题描述
我期待着与内容类型的POST请求设置为:
I am expecting a POST request with content type set to:
内容类型:应用程序/ x-WWW的形式urlen codeD
Content-Type: application/x-www-form-urlencoded
请求的身体看起来是这样的:
Request body looks like this:
FIRST_NAME =约翰&安培;姓氏=香蕉
first_name=john&last_name=banana
我的控制器动作有此签名:
My action on controller has this signature:
[HttpPost]
public HttpResponseMessage Save(Actor actor)
{
....
}
当演员类给出如下:
Where Actor class is given as:
public class Actor
{
public string FirstName {get;set;}
public string LastName {get;set;}
}
有没有办法来强制网页API绑定:
Is there a way to force Web API to bind:
FIRST_NAME =>姓结果
姓氏=>姓
first_name => FirstName
last_name => LastName
我知道如何与内容类型的请求设置为application / JSON做,但不能与urlen codeD。
I know how to do it with requests with content type set to application/json, but not with urlencoded.
推荐答案
我98%肯定(我看了源$ C $ c)该的WebAPI不支持它。
I'm 98% certain (I looked the source code) that WebAPI doesn't support it.
如果你真的需要支持不同的属性名称,您可以:
If you really need to support different property names, you can either:
-
到
演员
类,它作为别名添加附加属性。
Add additional properties to the
Actor
class which serves as alias.
创建自己的模型粘合剂。
Create your own model binder.
下面是一个简单的模型绑定:
Here is a simple model binder:
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;
}
}
如果你准备好迎接挑战,您可以尝试创建一个通用模型绑定。
If you are up for the challenge, you can try to create a generic model binder.
这篇关于网页API的形式,urlen codeD绑定到不同的属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!