You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core网站CKEditor内容去HTML标签显示解决方案求助

解决.NET Core网站CKEditor内容展示HTML标签问题

以下是几种实用的解决方法,可根据你的场景选择:

方法一:后端处理(推荐,更安全)

在.NET Core后端获取数据库数据后,将带HTML标签的内容转换为纯文本,再传递给视图展示。

方式1:使用内置工具类

引用Microsoft.AspNetCore.Html命名空间,利用HtmlUtilities.ConvertToPlainText方法:

using Microsoft.AspNetCore.Html;

// 从数据库获取原始内容
var rawDescription = yourEntity.Description;
// 转换为纯文本
var plainTextDescription = HtmlUtilities.ConvertToPlainText(rawDescription);
// 将plainTextDescription传入视图用于展示

方式2:自定义标签移除方法

如果需要更灵活的格式控制(比如保留换行),可以自己实现方法:

public static string StripHtml(string htmlContent)
{
    if (string.IsNullOrWhiteSpace(htmlContent)) return htmlContent;
    
    // 先替换HTML换行标签为文本换行,保留格式感知
    htmlContent = htmlContent.Replace("<br>", "\n")
                             .Replace("</p>", "\n\n")
                             .Replace("<p>", "");
    
    // 移除所有剩余HTML标签
    return System.Text.RegularExpressions.Regex.Replace(htmlContent, "<.*?>", string.Empty);
}

方法二:前端处理(适合静态展示场景)

如果需要在前端直接处理,可通过JavaScript解析HTML并提取纯文本:

原生JavaScript实现

function getPlainTextFromHtml(html) {
    const parser = new DOMParser();
    const doc = parser.parseFromString(html, 'text/html');
    return doc.body.textContent.trim();
}

// 调用示例:把带HTML的元素内容替换为纯文本
const descriptionElement = document.getElementById('description');
descriptionElement.textContent = getPlainTextFromHtml(descriptionElement.innerHTML);

jQuery简化实现

如果你项目中使用jQuery,可以用更简洁的代码:

$('#description').text($('#description').html());

注意事项

  • 优先选择后端处理:避免前端直接处理未过滤的HTML内容带来的XSS安全风险,后端可以提前完成内容净化。
  • 若需要保留部分格式(如段落、换行),可在处理逻辑中针对性替换对应HTML标签为文本格式符号。

内容的提问来源于stack exchange,提问作者Ashkan Amjad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 07:22:23