我有一个ActionFilterAttribute,我希望ViewModel的一个参数作为字符串。
我在" OnActionExecuting(HttpActionContext actionContext)"中阅读了它。方法
作为测试,我将此参数作为布尔值发送:true(而不是字符串且不带引号),但框架会自动将此true布尔值转换为" true"作为一个字符串。
有没有办法可以验证此输入参数是true还是" true"?
答案 0 :(得分:0)
因此,如果我理解正确,我认为你真正想要的是一个自定义模型绑定器。
public class NoBooleanModelBinder : IModelBinder
{
public bool BindModel(
HttpActionContext actionContext,
ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof(string))
{
return false; //we only want this to handle string models
}
//get the value that was parsed
string modelValue = bindingContext.ValueProvider
.GetValue(bindingContext.ModelName)
.AttemptedValue;
//check if that value was "true" or "false", ignoring case.
if (modelValue.Equals(bool.TrueString, StringComparison.OrdinalIgnoreCase) ||
modelValue.Equals(bool.FalseString, StringComparison.OrdinalIgnoreCase))
{
//add a model error.
bindingContext.ModelState.AddModelError(bindingContext.ModelName,
"Values true/false are not accepted");
//set the value that will be parsed to the controller to null
bindingContext.Model = null;
}
else
{
//else everything was okay so set the value.
bindingContext.Model = modelValue;
}
//returning true just means that our model binder did its job
//so no need to try another model binder.
return true;
}
}
然后你可以在你的Controller中做这样的事情:
public object Post([ModelBinder(typeof(NoBooleanModelBinder))]string somevalue)
{
if(this.ModelState.IsValid) { ... }
}