javascript - 在 ASP.Net Core 2 中存储和显示 HTML 字符串,同时避免使用 JS

标签 javascript asp.net-core asp.net-core-mvc asp.net-core-2.0

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

我如何设法将数据存储和显示/渲染为 HTML,同时过滤字符串中的任何 JS?

我尝试搜索 api,但找不到任何帮助。其次,现在仅使用类名来获取文档变得越来越困难,因此在答案中高度赞赏完整的类名。

最佳答案

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

@Html.Raw(Model.MyHtml)

识别发布的值是否包含任何 <script>标签和/或从值中删除它们,请使用 html 解析器,例如 Html Agility Pack 。例如,在 POST 方法中,您可以添加 ModelStateError并返回 View

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);

注意:如果您想为此使用正则表达式,我建议阅读 Regular Expression for Extracting Script Tags .

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

关于javascript - 在 ASP.Net Core 2 中存储和显示 HTML 字符串,同时避免使用 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50503360/

相关文章:

javascript - 从对象中拆分数组并在下划线模板中使用

javascript - 使用客户端的 fb api 发布到 Facebook 页面

asp.net-core - 当前不会命中切换断点。断点已设置但尚未绑定(bind)

.net - 尝试将 AutoMapper 添加到 .NetCore1.1 - 无法识别 services.AddAutoMapper()

visual-studio-2015 - 添加的新 Bower 包在关闭/打开之前不会显示在解决方案中

jwt token Multi-Tenancy

javascript:带有特殊字符的alt属性

javascript - js获取横向滚动事件

asp.net-core - 为什么 .Net Core 有自己的声明类型?

c# - 在 Windows 中运行 dotnet watch 时出错