public PolicyHtmlAttribute(FilterPolicy policy, string name, PolicyHtmlTag tag = null)
     : base(policy,name)
 {
     Tag = tag;
 }
Ejemplo n.º 2
0
        void ValidateAction(HtmlNode node,string tagName,PolicyHtmlTag tag)
        {
            HtmlNode parentNode = node.ParentNode;
            #region 过滤样式
            if ("style".Equals(tagName))
            {
                try
                {
                    node.FirstChild.InnerHtml = CssFilter.Filters(node.FirstChild.InnerHtml);
                }
                catch
                {
                    parentNode.RemoveChild(node);
                }
            }
            #endregion

            #region 过滤属性
            for (int currentAttributeIndex = 0; currentAttributeIndex < node.Attributes.Count; currentAttributeIndex++)
            {
                HtmlAttribute attribute = node.Attributes[currentAttributeIndex];
                string name = attribute.Name, _value = attribute.Value;
                var attr = tag.AllowedAttribute(name);

                #region 如果是白名单之外的属性移除掉
                if (attr == null)
                {
                    node.Attributes.Remove(name);
                    currentAttributeIndex--;
                    continue;
                }
                #endregion
                #region 元素内嵌样式
                if ("style".Equals(name, StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        attribute.Value = CssFilter.Filters(_value,true);
                    }
                    catch
                    {
                        node.Attributes.Remove(name);
                        currentAttributeIndex--;
                    }
                    continue;
                }
                #endregion
                ///如果未能通过验证,将执行指定的操作
                if (!FilterPolicy.ValidateAttribute(attr,_value))
                {
                    switch (attr.OnInvalid)
                    {
                        case PolicyHtmlAttributeOnInvalid.RemoveTag:
                            //删除当前的元素并退出函数
                            parentNode.RemoveChild(node);
                            return;
                        case PolicyHtmlAttributeOnInvalid.FilterTag:
                            ///删除当前节点,但保留其有效的子节点
                            PromoteChildren(node);
                            return;
                        default:
                            //删除当前的属性,指针往回调
                            node.Attributes.Remove(attr.Name);
                            currentAttributeIndex--;
                            break;
                    }

                }
            }
            #endregion
            ///过滤当前元素的子节点
            FiltersTags(node.ChildNodes);
        }