首页 > 解决方案 > 尽管采取了安全措施,但从表单中获取“潜在危险的 Request.Form 值”

问题描述

我的网站上有一个联系表格,一段时间以来我一直收到“从客户端检测到潜在危险的 Request.Form 值”的错误。

我已经采取了一些措施来试图阻止这些,包括:

模型:

[Required]
    [DataType(DataType.MultilineText)]
    [RegularExpression(@"^[a-zA-Z0-9!?£$'"",.&\-\s]+$", ErrorMessage = "Special characters are not allowed")]
    public string Message { get; set; }

看法

    @using (Html.BeginForm(null, null, FormMethod.Post, new { controller = "home", action = "Contact"}))
{
    @Html.AntiForgeryToken()

    <div class="form">
        <div class="form_inner">
            <div class="fieldset">
                @Html.TextAreaFor(model => model.Message, 8, 25, new { required = "required" })
                @Html.ValidationMessageFor(model => model.Message)
            </div>           
            <footer>
                @Html.HiddenFor(model => model.GoogleCaptchaToken)
                <input type="submit" value="Send Email" class="btn btn_submit" />
            </footer>
        </div>
    </div>
}

控制器

    [HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Contact(Contact model)
{
    if (ModelState.IsValid)
    {
        var isCaptchaValid = await IsCaptchaValid(model.GoogleCaptchaToken);

        if (isCaptchaValid)
        {
            _contactUsService.SendEmail(model);
        }
        else
        {
            ModelState.AddModelError("GoogleCaptcha", "The captcha is not valid");
        }            }

    return Redirect("/contact/thankyou");
}

然而,到目前为止,这些还没有成功阻止这些错误消息通过。

该错误从未说明已发布的整个消息,因此我看不到触发它的原因。我可以添加更多内容来防止这些通过,或者我可以看到从表格中发布的内容吗?

谢谢

标签: asp.netasp.net-mvcvalidationantiforgerytokenrequest.form

解决方案


我认为您遇到的问题是应用程序在检查您的正则表达式之前拒绝了该值。

您可以使用[AllowHtml]Attribute 允许输入将值传递给控制器​​,而不会因包含危险字符而被拒绝。

但是,您应该非常仔细地检查输入的值,因为此属性会禁用对该属性的验证。

您可以在此处阅读有关它的更多信息:Docs.Microsoft 中的 AllowHtmlAttribute 类


推荐阅读