【问题标题】:I get an HttpRequestValidationException even when I AllowHtml on the Model property即使我在 Model 属性上使用 AllowHtml,我也会收到 HttpRequestValidationException
【发布时间】:2015-10-13 15:34:53
【问题描述】:

我已允许在模型属性上使用 HTML,如下所示:

型号

public class FooViewModel
{
  [AllowHtml]
  public string Description { get; set; }
}

查看

@using (Html.BeginForm("EditDescription", "Foo", FormMethod.Post))
{
    @Html.AntiForgeryToken();

    <input type="hidden" value="@(Model != null && Model.Item1 != null ? Model.Item1 : string.Empty)" name="fooId" />

    <p>
        <textarea name="Description" cols="100" id="Description">
            @(Model != null && Model.Item2 != null ? Model.Item2 : string.Empty)
        </textarea>
    </p>

    <p><input type="submit" value="Submit" /></p>
}

@section Scripts {
    @Scripts.Render("~/bundles/nicEdit")

    <script type="text/javascript">
        bkLib.onDomLoaded(function()
        {
            new nicEditor({fullPanel : true}).panelInstance('Description');
        });
    </script>
    }

控制器

public class FooController
{
  public ActionResult EditDescription(string fooId)
  {
    if (Request.HttpMethod == "POST")
    {
      using (var context = new ApplicationDbContext())
      {
        var foo = context.Foos
                     .SingleOrDefault(f => f.Id == fooId);

        // I get the HttpRequestValidationException here
        foo.Description = Request["Description"];
        context.SaveChanges();

        return RedirectToAction("MyProfile");
      }
    }
  }
}

仍然,我收到请求验证异常。我什至尝试用 ValidateInput(false) 注释整个操作方法,因为 View 只有一个字段,这是模型上的单个属性,但我仍然不断收到异常。

我清除了 ASP.NET 临时文件和文件夹缓存,清理并重建了我的解决方案,但均无济于事。

【问题讨论】:

  • 您的基本代码有很多基本问题。你不应该使用 Request.HttpMethod 而应该使用HttpPost and Httpget。其次,您没有使用绑定来发回模型,因此您的属性几乎没用。
  • @ErikPhilips 我注意到所有这些。我从 MVC 版本 1 开始就一直在使用它。这个特定的操作和它的整个流程是我匆忙完成的,在与客户达成一致后,我们会回到它来修复它,现在是时候了。在您发表评论后,我通过分离每种方法的操作并实际发布回模型来修复它。我只是没有意识到(正如您推断的那样)请求验证与没有为每个 HTTP 请求提供单独的方法之间的相关性。

标签: asp.net asp.net-mvc asp.net-mvc-5.2


【解决方案1】:

更新您的代码以使用未验证版本的字符串,如下所示

foo.Description = Request.Unvalidated["Description"];

关于请求验证如何随着 MVC 发展以及为什么输入验证属性不起作用的很好读物 http://weblogs.asp.net/imranbaloch/understanding-request-validation-in-asp-net-mvc-3

【讨论】:

  • 感谢您的帮助和那篇文章。
猜你喜欢
  • 2021-05-26
  • 2011-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-21
  • 2021-01-23
  • 1970-01-01
相关资源
最近更新 更多