ComputerScience

Matthieu TUDURY… Just another WordPress site…

ASP.NET MVC3 et le ValidateInput(false)

Qui n'a pas rencontré le problème de validation sur ASP.NET MVC3 : A potentially dangerous Request.Form value was detected from the client.

En WebForm il est simple de corriger ce problème et je ne m'étendrait pas dessus de nombreux site décrive comment procéder.

En ASP.NET MVC3, l'attribut [ValidateInput(false)] sur la méthode de votre controlleur est sensé régler le problème.

Mais dans ce cas :

Test.cshtml

@{
    ViewBag.Title = "Test";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<h2>Test</h2>

<p>@Html.Raw( ViewBag.k)</p>

@using (Html.BeginForm())
{
<span style="font-size: 12px; line-height: 18px;">
</span>    <p><input type="text" name="toto" ><input type="submit" /></p>;
}

HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    [ValidateInput(false)]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!"+ Server.MachineName;

            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        [ValidateInput(false)]
        public ActionResult Test()
        {
            string k = "";

            foreach (string key in Request.Form.Keys)
            {
                k += key + " : " + Request.Form[key] + "; ";

            }
            ViewBag.k = k;

            return View();
        }
    }
}

si vous entrez le texte : ” coucou bonjour” dans le champ texte, et que vous soumettez le formulaire par un clic sur le bouton Valider, Malgré l'utilisation des attributs [ValidateInput(false)], Vous aurez la page habituelle d'erreure…

[HttpRequestValidationException (0x80004005): A potentially dangerous Request.Form value was detected from the client (toto="<fdfdsdf>").]
   System.Web.HttpRequest.ValidateString(String value, String collectionKey, RequestValidationSource requestCollection) +8812804
   Microsoft.Web.Infrastructure.DynamicValidationHelper.<>c__DisplayClass12.<ReplaceCollection>b__d(String value, String key) +79
   Microsoft.Web.Infrastructure.DynamicValidationHelper.LazilyEvaluatedNameObjectEntry.ValidateObject() +89
   Microsoft.Web.Infrastructure.DynamicValidationHelper.LazilyValidatingHashtable.get_Item(Object key) +54

La solution :

Utilisez la classe System.Web.Helpers.Validation :

foreach (string key in System.Web.Helpers.Validation.Unvalidated(Request).Form.Keys)
{
     k += key + " : " + System.Web.Helpers.Validation.Unvalidated(Request).Form[key] + "; ";
}

Vous n'aurez ainsi plus d'erreurs de validation.