代码之家  ›  专栏  ›  技术社区  ›  Praveen Rai

在ASP.NET核心2中存储和显示HTML字符串,同时避免JS

  •  0
  • Praveen Rai  · 技术社区  · 7 年前

    我希望使用富文本编辑器(quilljs)存储格式化的文本,在显示时应该将其呈现为HTML。默认情况下,视图对HTML进行编码以避免JS注入,因此数据被视为普通字符串。

    如何在过滤字符串中的任何JS的同时,将数据存储和显示/呈现为HTML?

    我试图搜索API,但找不到任何帮助。第二,如今,仅仅用类名来获取文档变得越来越困难,因此在答案中非常感谢完整的类名。

    2 回复  |  直到 7 年前
        1
  •  1
  •   user3559349    7 年前

    假设您的模型包含 public string MyHtml { get; set; } 属性,然后要在视图中显示结果,请使用

    @Html.Raw(Model.MyHtml)
    

    确定已过账的值是否包含 <script> 标记和/或要从值中移除它们,请使用HTML解析器,例如 Html Agility Pack . 例如,在post方法中,可以添加 ModelStateError 并返回视图

    public ActionResult Save(MyModel model)
    {
        if (HasScripts(model.MyHtml)
        {
            ModelState.AddModelError("MyHtml", "The html cannot contain script tags");
        }
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        // save and redirect
    }
    

    在哪里? HasScripts()

    public bool HasScripts(string html)
    {
        HtmlDocument document = new HtmlDocument();
        document.LoadHtml(html);
        HtmlNode root = document.DocumentNode;
        return root.Descendants("script").Any();
    }
    

    或者,如果您只想在保存之前删除它们,可以使用以下方法

    public string RemoveScripts(string html)
    {
        HtmlDocument document = new HtmlDocument();
        document.LoadHtml(html);
        HtmlNode root = document.DocumentNode;
        IEnumerable<HtmlNode> scripts = root.Descendants("script");
        for(int i = 0; i < scripts.Count(); i++)
        {
            HtmlNode script = scripts[i];
            script.Remove();
        }
        return scripts.Any() ? document.ToString() : html;
    }
    

    把它当作

    model.MyHtml = RemoveScripts(model.MyHtml);
    

    注意:如果您想使用regex,我建议您阅读 Regular Expression for Extracting Script Tags .

    您可能还需要考虑检查其他潜在恶意元素,如 <embed> , <iframe> , <form>

        2
  •  0
  •   Pang Ajmal PraveeN    7 年前

    不使用 @Html.Raw(...) . 用户可以执行javascript注入。有许多库可以防止JS注入。我使用了反XS来显示HTML。

    反X: https://www.nuget.org/packages/AntiXSS/