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

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

捕获异常并显示

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

我觉得不够专业。

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

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

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


当前回答

这些建议对我都不起作用。无论如何,我不想关闭整个网站的这个功能,因为99%的时间我不希望我的用户在web表单上放置HTML。我刚刚创建了自己的变通方法,因为我是唯一一个使用这个特定应用程序的人。我在后面的代码中将输入转换为HTML并将其插入数据库。

其他回答

如果您确实需要特殊字符,如,>,<等,请禁用页面验证。然后确保在显示用户输入时,数据是HTML编码的。

页面验证存在安全漏洞,因此可以绕过它。此外,不应仅依赖页面验证。

参见:http://web.archive.org/web/20080913071637/http://www.procheckup.com:80/PDFs/bypassing-dot-NET-ValidateRequest.pdf

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

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

您可以在自定义模型活页夹中自动对字段进行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();
   }
}   

前面的答案很好,但没有人说过如何排除一个字段进行HTML/JavaScript注入的验证。我不知道以前的版本,但在MVC3 Beta版中,您可以这样做:

[HttpPost, ValidateInput(true, Exclude = "YourFieldName")]
public virtual ActionResult Edit(int id, FormCollection collection)
{
    ...
}

这仍然会验证除排除的字段之外的所有字段。这一点的好处是,您的验证属性仍然验证字段,但您没有得到“潜在危险的请求。表单值已从客户端检测到”异常。

我已经用它验证了正则表达式。我制作了自己的ValidationAttribute,以查看正则表达式是否有效。由于正则表达式可以包含类似于脚本的内容,我应用了上面的代码-正则表达式仍然在检查是否有效,但不检查是否包含脚本或HTML。

这里的其他解决方案很好,但必须将[AllowHtml]应用于每个Model属性,特别是如果您在一个规模适中的网站上拥有超过100个模型,这有点麻烦。

如果像我一样,你想在整个站点范围内关闭这个(IMHO非常无意义)功能,你可以在基本控制器中重写Execute()方法(如果你还没有基本控制器,我建议你做一个,它们对于应用公共功能非常有用)。

    protected override void Execute(RequestContext requestContext)
    {
        // Disable requestion validation (security) across the whole site
        ValidateRequest = false;
        base.Execute(requestContext);
    }

只需确保您对从用户输入输出到视图的所有内容进行了HTML编码(无论如何,这是ASP.NET MVC 3中使用Razor的默认行为,因此除非出于某种奇怪的原因,您使用HTML.Raw(),否则不应该需要此功能。