我希望使用富文本编辑器 (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/