OnActionExecuting actionContext绑定bool参数转字符串

OnActionExecuting actionContext binding bool parameter turned string

我有一个 ActionFilterAttribute,我希望 ViewModel 的其中一个参数是字符串。

我是用"OnActionExecuting(HttpActionContext actionContext)"方法读的

作为测试,我将此参数作为布尔值发送:true(而不是字符串且不带引号),但框架会自动将此 true 布尔值转换为 "true" 作为字符串。

有什么方法可以验证这个输入参数是真值还是 "true"?

因此,如果我理解正确的话,我认为您真正想要的是自定义模型活页夹。

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;
    }
}

然后你可以在你的控制器中做这样的事情:

public object Post([ModelBinder(typeof(NoBooleanModelBinder))]string somevalue)
{
    if(this.ModelState.IsValid) { ... }
}