C# web api操作参数将空字符串参数转换为null
我有一些带有很多字符串参数的web Api操作。对于其中一些参数,客户端发送空字符串而不是null,但我需要在数据库中保存null以防空字符串。我尝试使用model binder和JSONconvertor,但失败了C# web api操作参数将空字符串参数转换为null,c#,rest,asp.net-web-api,asp.net-web-api-routing,C#,Rest,Asp.net Web Api,Asp.net Web Api Routing,我有一些带有很多字符串参数的web Api操作。对于其中一些参数,客户端发送空字符串而不是null,但我需要在数据库中保存null以防空字符串。我尝试使用model binder和JSONconvertor,但失败了 供参考;我需要一个通用解决方案,因为我不希望在方法体中检查参数并将其替换为null。您可以使用字符串属性上的DisplayFormat属性自动将空字符串转换为null [DisplayFormat(ConvertEmptyStringToNull = true)] public s
供参考;我需要一个通用解决方案,因为我不希望在方法体中检查参数并将其替换为null。您可以使用字符串属性上的DisplayFormat属性自动将空字符串转换为null
[DisplayFormat(ConvertEmptyStringToNull = true)]
public string MyString { get; set; }
谢谢Sarathy,你的解决方案也可能有效,但我以以下解决方案结束: 1) 创建自定义模型绑定器,如下所示
public class EmptyStringModelBinder : System.Web.Mvc.IModelBinder
{
public object BindModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
{
string key = bindingContext.ModelName;
ValueProviderResult val = bindingContext.ValueProvider.GetValue(key);
if (val != null)
{
var s = val.AttemptedValue as string;
if (s != null && (s.IsEmpty() || s.Trim().IsEmpty()))
{
return null;
}
return val.AttemptedValue;
}
return null;
}
}
2) 使用ModelBinder属性标记操作方法参数
public ActionResult UpdateAttribute(int id,
int AttributeTypeId,
int? Number_Value,
decimal? Money_Value,
[ModelBinder(typeof(EmptyStringModelBinder))]string Text_Value)
或者您可以在配置时添加此模型绑定器。它将检查所有字符串参数并将空字符串替换为null(可能不需要)如果您在string属性上使用
[必需]
属性,但使其在数据库中为null,WebApi将把它在Json中接收的空字符串转换为null值
我的要求正好相反。我在数据库中有一个不可为空的字段,希望将空字符串保存到数据库中。对于这个需求,我必须删除[Required]
属性,并添加[DisplayFormat(ConvertEmptyStringToNull=false)]
然后JSON中的空字符串被保存到数据库中。对于中的问题,我已经回答了类似的问题。您可以在action arguments dictionary中只找到空字符串参数(如果参数类型为string)并将其替换为null,而不是创建新实例。谢谢。您的解决方案也可以使用,但我开发了一个自定义模型活页夹。见下文。再次感谢Hanks的否决票,尽管它适用于WebAPI。在给你否决票之前,我已经测试过了。如果你能举出一个有效的例子,我很乐意把它还原为一个向上投票。我需要这个确切的功能,但无法让它工作。我刚刚让它工作,你必须把它放在你的实体框架poco上(在我的例子中,代码是第一个数据库实体)。我的视图模型将其解析为空字符串“”。。使用此注释,当它尝试将其持久化到数据库时,它将其更改为null。谢谢你,贾斯汀。它对于WebAPI的验证任务非常方便,通常需要在检查
ModelState.IsValid
之前将所有内容准备就绪。我的案子和肖恩的要求一模一样。但是有大约一千个模型,最多有150个属性。我没有为每个属性使用DisplayFormat
,而是采用了这样的解决方案: