0

私はActionModelのいずれかのパラメータを文字列として使用すると期待しているActionFilterAttributeを持っています。OnActionExecuting actionContextバインディングboolパラメータは文字列に変換されました

「OnActionExecuting(HttpActionContext actionContext)」メソッドで読みました。

私はこのパラメータをブール値として送信しています:true(文字列ではなく、引用符なし)ですが、フレームワークは自動的にこの真偽値を文字列として "true"に変換します。

この入力パラメータが真であるか真であることを検証する方法はありますか?

+0

が '' OnActionExecutingは(HttpActionContextするactionContext) 'WebAPIのフィルタであると' OnActionExecuting(ActionExecutingContextするactionContext)としてこのMVCやWebAPIのでしょうですMVCですか?間違ったタイプの 'ActionFilterAttribute'を持つ可能性があります。これがMVCかWebAPIかどうかを確認できれば、私は例を挙げることができます。 –

+0

ウェブAPIです。私は、文字列を期待しているコントローラにブール値を送信すると、フレームワークは真のブール値を「真の」文字列に変換します。私はこれがフレームワークによってボックスから外されたと思いますが、私はこれを制御して、文字列の代わりにboolを送信すると、検証メッセージを表示したいと思います。 – user441365

答えて

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

次に、あなたがあなたのコントローラでこのような何かを行う可能性があります:

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

ああ、デフォルトのモデルバインダーをオーバーライドする必要があります。ブール値を自動的に文字列に変換する必要はありません。このケースをどのように扱うかを見るためにソースコードを見ていきます。ありがとう – user441365

+0

ええ、このモデルのバインダーは、型が 'bindingContext.ModelType!= typeof(string)'の文字列であることを意味するかどうかをチェックし、その型が文字型であるかどうかをチェックします。 'false'。 –

+0

これは過度なことかもしれないし、ちょうどその価値を認めていると思いますか? –

関連する問題