在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而不是对象。
如何在WebApi版本的IModelBinder中更改字符串值?
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;
}
}发布于 2015-11-20 11:13:00
您将设置bindingContext.Model并返回true
var value = result.AttemptedValue.Trim().ToUpper();
bindingContext.Model = value;
return true;当然,这是假设您的模型只是一个字符串。否则,可能需要更多的对象创建/转换。
https://stackoverflow.com/questions/33825118
复制相似问题