客户截断Querystring会导致FormatException

Dus*_*sda 6 c# asp.net-mvc

在Rentler,我们经常看到错误

System.FormatException,String未被识别为有效的布尔值

在我们的健康监测中.事实证明,看起来我们的客户偶尔会在其他地方复制/粘贴网址时截断网址的末尾.恰好,布尔参数往往位于字符串的末尾,当客户通过某个社交网络共享它时,我们会收到错误报告.

https:// {domain}/search?sid = 17403777&nid = 651&location = 840065&propertytypecode = 1&photosonly = fals

我们对所有东西使用模型绑定,所以我不确定如何处理这个问题.我可以将属性更改为字符串并尝试在控制器操作中解析它,但这很邋..是否有任何简单,流畅的方式将模型绑定器提供给TryParse()它,如果它不能解决为false?

pkm*_*iec 1

布尔数据类型的自定义模型绑定器怎么样?你需要这样的东西:

/// <summary>
/// A custom model binder for boolean values. This behaves the same as the default
/// one, except it will resolve the value to false if it cannot be parsed.
/// </summary>
public class BooleanModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        //MVC checkboxes need specific handling in checked state
        if (string.Equals(valueResult.AttemptedValue, "true,false"))
        {
            AddToModelState(bindingContext, valueResult);
            return true;
        }

        bool parsed = false;
        if (Boolean.TryParse(valueResult.AttemptedValue, out parsed))
        {
            AddToModelState(bindingContext, valueResult);
            return parsed;
        }

        return false;
    }

    private static void AddToModelState(ModelBindingContext bindingContext, ValueProviderResult valueResult)
    {
        bindingContext.ModelState.Add(bindingContext.ModelName, new ModelState { Value = valueResult });
    }
}

//in Global.asax
protected void Application_Start()
{
    ...
    ModelBinders.Binders.Add(typeof(bool), new BooleanModelBinder());
}
Run Code Online (Sandbox Code Playgroud)