7

Rentler では、エラーが頻繁に発生します。

System.FormatException、文字列が有効なブール値として認識されませんでした

私たちの健康モニタリングで。結局のところ、お客様が URL を別の場所にコピー/貼り付けする際に、URL の末尾を切り捨てる場合があるようです。ブール値のパラメーターが文字列の末尾にある傾向があり、顧客がそれをソーシャル ネットワークで共有すると、エラー レポートが表示されます。

https://{ドメイン}/search?sid=17403777&nid=651&location=840065&propertytypecode=1& photosonly=fals

私たちはすべてにモデル バインディングを使用しているため、これをどのように処理すればよいかわかりません。プロパティを文字列に変更し、コントローラー アクションで解析を試みることもできますが、それは適切ではありません。モデルバインダーをTryParse()に取得し、それができない場合はfalseに解決する簡単で流暢な方法はありますか?

4

2 に答える 2

1

boolean データ型のカスタム モデル バインダーはどうですか? 次のようなものが必要です。

/// <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());
}
于 2012-10-15T18:14:30.200 に答える
0

いつでも try/catch ブロックを追加して、catch にデフォルト値を設定できます。

別の方法は、パラメーターの最初の文字が「T」または「F」であるかどうかのみを確認することです。これにより、多くの問題が回避されるはずです。

于 2012-10-15T18:46:55.530 に答える