【问题标题】:Sanitising ASP.NET input (allowing angle brackets)清理 ASP.NET 输入(允许尖括号)
【发布时间】:2014-01-02 11:31:40
【问题描述】:

我已阅读有关为 ASP.NET 请求自定义输入验证以避免可怕的“检测到潜在危险值”的信息。我正在使用以下代码来允许尖括号通过验证。

public class RequestValidator : System.Web.Util.RequestValidator {
    protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex) {
        validationFailureIndex = 0;

        switch (requestValidationSource) {
            case RequestValidationSource.Form:
                if (control is CustomTextBox) { // How can I get the control?
                    // allow angle brackets to pass validation
                    value = value.Replace("<", "&lt;").Replace(">", "&gt;");
                }
                break;
        }

        return base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex);
    }
}

现在我允许这些具有潜在危险的值通过验证过滤器,我希望确定它们得到了正确处理。这是一个 Web 窗体环境,所以我想创建一个 CustomTextBox 控件,覆盖 Text 属性和 HtmlEncode 字符串。

从上面代码中的注释可以看出,我想限制我的RequestValidator,以便它只允许“危险”值通过验证,前提是我可以确定它们将由我的CustomTextBox。当我们只需要 valuecollectionKey 时,我如何才能获得对 Control 的引用?

【问题讨论】:

    标签: c# asp.net validation webforms


    【解决方案1】:

    表单键的验证甚至在页面PreInit 事件之前发生。当时没有创建控件。

    我认为您最好的机会是持有当前页面上存在的所有 CustomTextBox 实例的唯一 ID 集合。拥有该集合后,您可以检查正在验证的表单键是否存在于集合中,这意味着它实际上是 CustomTextBox

    该集合可以在CustomTextBox 控件内进行管理,并保存在会话或应用程序缓存中。

    【讨论】:

    • 我认为可能是这种情况,因为即使context.Handler 为空。这可能会解决单个页面的问题,但我正在寻找更通用的解决方案,以便将其合并到库中
    • @Red Taz:你的意思是你可以在两个不同的页面上有两个具有相同 UniqueID 的控件,其中只有一个是 CustomTextBox?
    • 理论上是的。此外,为了使列表的维护自动化;每次应用程序启动时,您都需要枚举每个页面上的所有控件并将结果存储在内存中
    • 我认为 CustomTextBox 的每个实例都可以在第一次创建时将自己注册到列表中。此列表也可以是Dictionary&lt;string,List&lt;string&gt;&gt;,其中键是页面,值是该页面的 UniqueID 列表。为了帮助避免冲突,您可以向 CustomTextBox 控件添加另一个 ID 层,例如 Panel。
    【解决方案2】:

    我建议在您的自定义控件构造函数中将ValidateRequestMode 属性显式设置为ValidateRequestMode.Disabled 并覆盖Text 属性(或任何用于存储值的属性)getter 并根据您的具体情况返回经过清理的值场景。

    【讨论】:

      猜你喜欢
      • 2012-02-03
      • 1970-01-01
      • 1970-01-01
      • 2016-01-31
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多