每当用户在我的web应用程序中的页面中发布包含<或>的内容时,我都会引发此异常。

我不想因为有人在文本框中输入了字符而引发异常或使整个web应用程序崩溃,但我正在寻找一种优雅的方式来处理这一问题。

捕获异常并显示

出现错误,请返回并重新键入整个表单,但这次请不要使用<

我觉得不够专业。

禁用后验证(validateRequest=“false”)肯定可以避免此错误,但这会使页面容易受到许多攻击。

理想情况下:当发生包含HTML限制字符的回发时,表单集合中的回发值将自动进行HTML编码。因此,我的文本框的.Text属性将是&lt;html&gt;

有没有办法让我从处理者那里做到这一点?


当前回答

我找到了一个使用JavaScript编码数据的解决方案,数据在.NET中解码(不需要jQuery)。

使文本框成为HTML元素(如文本区域)而不是ASP元素。添加隐藏字段。将以下JavaScript函数添加到标头中。函数boo(){targetText=document.getElementById(“HiddenField1”);sourceText=document.getElementById(“userbox”);targetText.value=转义(sourceText.innerText);}

在文本区域中,包含一个调用boo()的onchange:

<textarea id="userbox"  onchange="boo();"></textarea>

最后,在.NET中,使用

string val = Server.UrlDecode(HiddenField1.Value);

我知道这是单向的-如果你需要双向的,你必须要有创造性,但如果你不能编辑web.config,这就提供了一个解决方案

下面是我(MC9000)通过jQuery创建并使用的示例:

$(document).ready(function () {

    $("#txtHTML").change(function () {
        var currentText = $("#txtHTML").text();
        currentText = escape(currentText); // Escapes the HTML including quotations, etc
        $("#hidHTML").val(currentText); // Set the hidden field
    });

    // Intercept the postback
    $("#btnMyPostbackButton").click(function () {
        $("#txtHTML").val(""); // Clear the textarea before POSTing
                               // If you don't clear it, it will give you
                               // the error due to the HTML in the textarea.
        return true; // Post back
    });


});

以及标记:

<asp:HiddenField ID="hidHTML" runat="server" />
<textarea id="txtHTML"></textarea>
<asp:Button ID="btnMyPostbackButton" runat="server" Text="Post Form" />

这很有效。如果黑客试图绕过JavaScript发帖,他们只会看到错误。您还可以将所有这些编码的数据保存在数据库中,然后(在服务器端)对其进行解析,并在其他地方显示之前分析和检查攻击。

其他回答

您可以在自定义模型活页夹中自动对字段进行HTML编码。我的解决方案有些不同,我将错误放在ModelState中,并在字段附近显示错误消息。很容易修改此代码以自动编码

 public class AppModelBinder : DefaultModelBinder
    {
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            try
            {
                return base.CreateModel(controllerContext, bindingContext, modelType);
            }
            catch (HttpRequestValidationException e)
            {
                HandleHttpRequestValidationException(bindingContext, e);
                return null; // Encode here
            }
        }
        protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext,
            PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
        {
            try
            {
                return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
            }
            catch (HttpRequestValidationException e)
            {
                HandleHttpRequestValidationException(bindingContext, e);
                return null; // Encode here
            }
        }

        protected void HandleHttpRequestValidationException(ModelBindingContext bindingContext, HttpRequestValidationException ex)
        {
            var valueProviderCollection = bindingContext.ValueProvider as ValueProviderCollection;
            if (valueProviderCollection != null)
            {
                ValueProviderResult valueProviderResult = valueProviderCollection.GetValue(bindingContext.ModelName, skipValidation: true);
                bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);
            }

            string errorMessage = string.Format(CultureInfo.CurrentCulture, "{0} contains invalid symbols: <, &",
                     bindingContext.ModelMetadata.DisplayName);

            bindingContext.ModelState.AddModelError(bindingContext.ModelName, errorMessage);
        }
    }

在应用程序启动中:

ModelBinders.Binders.DefaultBinder = new AppModelBinder();

请注意,它仅适用于表单字段。危险值未传递到控制器模型,但存储在ModelState中,可以在表单上重新显示错误消息。

URL中的危险字符可以这样处理:

private void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    HttpContext httpContext = HttpContext.Current;

    HttpException httpException = exception as HttpException;
    if (httpException != null)
    {
        RouteData routeData = new RouteData();
        routeData.Values.Add("controller", "Error");
        var httpCode = httpException.GetHttpCode();
        switch (httpCode)
        {
            case (int)HttpStatusCode.BadRequest /* 400 */:
                if (httpException.Message.Contains("Request.Path"))
                {
                    httpContext.Response.Clear();
                    RequestContext requestContext = new RequestContext(new HttpContextWrapper(Context), routeData);
                    requestContext.RouteData.Values["action"] ="InvalidUrl";
                    requestContext.RouteData.Values["controller"] ="Error";
                    IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
                    IController controller = factory.CreateController(requestContext, "Error");
                    controller.Execute(requestContext);
                    httpContext.Server.ClearError();
                    Response.StatusCode = (int)HttpStatusCode.BadRequest /* 400 */;
                }
                break;
        }
    }
}

错误控制器:

public class ErrorController : Controller
 {
   public ActionResult InvalidUrl()
   {
      return View();
   }
}   

如何在ASP.NET 4.6.2中修复AjaxExtControls的此问题:

我们在AjaxExtControls富文本编辑器中遇到了同样的问题。此问题在从.NET 2.0升级到.NET 4.5后立即开始。我查看了SOF的所有答案,但没有找到一个不损害.NET4.5提供的安全性的解决方案。

修复1(不推荐,因为它会降低应用程序的安全性):我在requestValidationMode=“2.0,它起了作用,但我担心安全特性。因此,这是一个修复,就像降低了整个应用程序的安全性。

修复2(推荐):由于这个问题只发生在AjaxExtControl中的一个,我最终能够使用下面的简单代码解决这个问题:

editorID.value = editorID.value.replace(/>/g, "&gt;");
editorID.value = editorID.value.replace(/</g, "&lt;");

在向服务器发送请求之前,在客户端(javascript)上执行此代码。注意,editorID不是我们在html.aspx页面上的ID,而是AjaxExtControl内部使用的富文本编辑器的ID。

对于ASP.NET 4.0,您可以将标记全部放在<location>元素中,从而允许标记作为特定页面的输入,而不是整个站点的输入。这将确保所有其他页面都是安全的。您不需要在.aspx页面中放入ValidateRequest=“false”。

<configuration>
...
  <location path="MyFolder/.aspx">
    <system.web>
      <pages validateRequest="false" />
      <httpRuntime requestValidationMode="2.0" />
    </system.web>
  </location>
...
</configuration>

在web.config中控制这一点更安全,因为您可以在站点级别看到哪些页面允许标记作为输入。

您仍然需要在禁用请求验证的页面上以编程方式验证输入。

您还可以使用JavaScript的转义(字符串)函数来替换特殊字符。然后服务器端使用server.URLDecode(字符串)将其切换回来。

这样,您就不必关闭输入验证,其他程序员将更清楚地知道字符串可能包含HTML内容。

您可以使用以下内容:

var nvc = Request.Unvalidated().Form;

稍后,nvc[“yourKey”]应该会起作用。