在 Asp.Net MVC 中,System.Web.Mvc.IModelBinder 允许以下实现更改所有字符串:
public class CustomMvcTextBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ValueProviderResult result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (result == null)
return null;
var value = result.AttemptedValue.Trim().ToUpper();
return value;
}
}
然后我将其添加到 ModelBinders 中:
ModelBinders.Binders.Add(typeof(string), new CustomMvcTextBinder());
然而,Asp.Net WebApi 实现 System.Web.Http.ModelBinding.IModelBinder 有一个不同的实现,返回 bool 而不是对象。
如何更改 IModelBinder WebApi 版本中的字符串值?
public class CustomWebApiTextBinder : IModelBinder
{
public bool BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ValueProviderResult result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (result == null)
return false;
var value = result.AttemptedValue.Trim().ToUpper();
return true;
}
}
最佳答案
您将设置bindingContext.Model
并返回true
:
var value = result.AttemptedValue.Trim().ToUpper();
bindingContext.Model = value;
return true;
当然,这是假设您的模型只是一个字符串。否则可能需要更多的对象创建/转换。
关于asp.net - WebApi 字符串操作中的 IModelBinder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33825118/