C# Web API表单URL编码绑定到不同的属性名称
我期待内容类型设置为以下的POST请求: 内容类型:application/x-www-form-urlencoded 请求主体如下所示: 名字=约翰&姓氏=香蕉 我对控制器的操作具有以下签名:C# Web API表单URL编码绑定到不同的属性名称,c#,asp.net-web-api,C#,Asp.net Web Api,我期待内容类型设置为以下的POST请求: 内容类型:application/x-www-form-urlencoded 请求主体如下所示: 名字=约翰&姓氏=香蕉 我对控制器的操作具有以下签名: [HttpPost] public HttpResponseMessage Save(Actor actor) { .... } 其中,Actor类如下所示: public class Actor { public string FirstName {get;set;} public stri
[HttpPost]
public HttpResponseMessage Save(Actor actor)
{
....
}
其中,Actor类如下所示:
public class Actor
{
public string FirstName {get;set;}
public string LastName {get;set;}
}
有没有办法强制Web API绑定:
first_name=>FirstNamelast_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;
}
}
如果你愿意接受挑战,你可以尝试创建一个通用的模型绑定器。这是一篇老文章,但也许这可以帮助其他人。 这是一个 它可以这样使用:
[ModelBinder(typeof(AliasBinder))]
public class MyModel
{
[Alias("state")]
public string Status { get; set; }
}
请毫不犹豫地评论我的代码:)
每个想法/评论都是受欢迎的。虽然这是非常特定于类的解决方案,这意味着我必须为每个类实现这一点,而不是创建通用的方法,但我会接受这一点作为您努力的答案。但是,如果您提出了更好的可重用方法,请发布:)我之前查看了WebAPI源代码,发现创建可重用版本需要很多努力。我,您提出了更好的解决方案吗?谢谢。@BarbarosAlp不。我两年前就停止使用WebAPI了!您确定这适用于web api模型绑定吗?我认为这是特定于MVC的。请纠正我,如果我错了,因为我需要一个解决方案来解决这个问题,但不认为这个解决方案可以为web api工作