【问题标题】:OnActionExecuting actionContext binding bool parameter turned stringOnActionExecuting actionContext 绑定 bool 参数转字符串
【发布时间】:2017-11-28 21:41:48
【问题描述】:

我有一个 ActionFilterAttribute,我希望 ViewModel 的参数之一为字符串。

我是在“OnActionExecuting(HttpActionContext actionContext)”方法中读到的。

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

有没有办法验证这个输入参数是真还是“真”?

【问题讨论】:

  • 这是 MVC 还是 WebAPI,因为 OnActionExecuting(HttpActionContext actionContext) 是 WebAPI 过滤器,OnActionExecuting (ActionExecutingContext actionContext) 是 MVC?您的ActionFilterAttribute 类型可能有误。如果您可以确认这是 MVC 还是 WebAPI,那么我可以举个例子。
  • 它是 web api。当我将布尔值发送到期望字符串的控制器时,框架会将真正的布尔值转换为“真”字符串。我想这是由框架开箱即用的,但我想控制它并在他们发送布尔而不是字符串时显示验证消息

标签: asp.net-mvc asp.net-web-api data-binding model-validation


【解决方案1】:

所以如果我理解正确,我认为您真正想要的是自定义模型绑定器。

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) { ... }
}

【讨论】:

  • 啊,所以也许我需要做的是覆盖默认模型绑定器。我不希望它自动将布尔值转换为字符串。我将查看源代码以了解如何处理这种情况。谢谢
  • 是的,所以这个模型绑定器将检查类型是否意味着是带有bindingContext.ModelType != typeof(string) 的字符串,然后如果类型意味着是字符串,则检查该类型不是true 或@987654325 @.
  • 我会说这可能是矫枉过正,只允许值?
  • 我可能最终会忽略它,是的,但我想看看是否可以不费吹灰之力地做到这一点
猜你喜欢
  • 1970-01-01
  • 2014-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-22
  • 2015-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多