2017-06-05 9 views
1

フォームバリデーション( "application/x-www-form-urlencoded")に一貫した方法でコンテンツタイプ "application/json"でRequestValidationを実行したいと思っています。 )。ASP.Net RequestValidation for json POSTがフォームRequestValidationに一致するように

私はhttps://msdn.microsoft.com/en-us/library/system.web.util.requestvalidator(v=vs.110).aspxを読んだことがありますが、それほど助けにはなりませんでした。

私は、デフォルトのSystem.Web.Util.RequestValidatorを置き換えるカスタムリクエストバリデーターを実装しようとしています。

私は入力が一貫私はおそらくコントローラにJSONを送信する機能を削除し、フォームを通じて、すべてを強制的に検証することができない場合、私はまたhttps://msdn.microsoft.com/en-us/library/system.web.util.requestvalidator(v=vs.110).aspx

見てきた - 私は「として理想的ではありませんjsonを受け入れるためのいくつかの方法が好きです。

私はすでに出力をエンコードしていますが、フォームとjsonの入力を検証し、理想的に一貫して防御したいと考えています。

残念なことに、これに関する多くのMSDNドキュメントは、古くなっており、現在は無関係です。

参考までに.net 4.6.1を使用しています。

このようにリクエストを検証して検証するのは合理的ですか?

+0

[カスタム要求の検証](https://msdn.microsoft.com/en-us/library/system.web.util。 requestvalidationsource(v = vs.110).aspx)助けて欲しい –

答えて

0

最後に、私はModelBinderが...これがこのhttps://weblogs.asp.net/imranbaloch/security-issue-in-asp-net-mvc3-jsonvalueproviderfactoryを読んでの組み合わせであり、このhttps://gist.github.com/jamescrowley/b8c0c006e7b00e28cbbf

それはそれのように見えるように要求(RequestValidationSource.Form)のソースを変更するカスタムを実装しました同じパイプラインで検証することができます。

public class JsonValidatingModelBinder : DefaultModelBinder 
{ 
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     var result = base.BindModel(controllerContext, bindingContext); 
     if (!IsJsonRequest(controllerContext)) 
     { 
      return result; 
     } 
     if (!bindingContext.ModelMetadata.RequestValidationEnabled) 
     { 
      return result; 
     } 
     if (result != null) 
     { 
      EnsureRequestFieldIsValid(controllerContext, result); 
     } 
     return result; 
    } 

    static void EnsureRequestFieldIsValid(ControllerContext controllerContext, object result) 
    { 
     int index; 
     // abusing RequestValidationSource enum 
     if (!RequestValidator.Current.InvokeIsValidRequestString(
      controllerContext.HttpContext.ApplicationInstance.Context, 
      result.ToString(), RequestValidationSource.Form, null, out index)) 
     { 
      throw new HttpRequestValidationException(
       "A potentially dangerous value was detected from the client "); 
     } 
    } 

    static bool IsJsonRequest(ControllerContext controllerContext) 
    { 
     return controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase); 
    } 

とGlobal.asaxの中...

protected void Application_Start() 
    { 
     System.Web.Mvc.ModelBinders.Binders.DefaultBinder = new JsonValidatingModelBinder(); 

    } 
関連する問題