You need to enable JavaScript to run this app. ASP.NET Core Razor Pages如何实现长文本含搜索词片段的展示功能
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core Razor Pages如何实现长文本含搜索词片段的展示功能

实现步骤

你可以通过封装字符串扩展方法的方式统一处理搜索摘要的截断和高亮逻辑,具体实现如下:

1. 封装高亮摘要生成扩展方法

在项目中新增字符串扩展类,统一处理匹配定位、截断、高亮替换逻辑,支持大小写不敏感匹配:

using Microsoft.AspNetCore.Html;
using System;
using System.Text.RegularExpressions;
using System.Web;

public static class SearchSummaryExtension
{
    /// <param name="contextLength">搜索词前后保留的上下文字符数,可根据页面展示需求调整</param>
    public static IHtmlContent ToSearchSummary(this string originalText, string searchKeyword, int contextLength = 20)
    {
        // 空内容直接返回
        if (string.IsNullOrWhiteSpace(originalText) || string.IsNullOrWhiteSpace(searchKeyword))
            return new HtmlString(HttpUtility.HtmlEncode(originalText ?? string.Empty));

        // 防XSS:先对原文本做HTML编码
        var encodedText = HttpUtility.HtmlEncode(originalText);
        var encodedKeyword = HttpUtility.HtmlEncode(searchKeyword);

        // 匹配搜索词位置,忽略大小写
        var matchResult = Regex.Match(encodedText, Regex.Escape(encodedKeyword), RegexOptions.IgnoreCase);
        
        // 无匹配结果返回前N个字符加省略号
        if (!matchResult.Success)
        {
            return encodedText.Length <= contextLength * 2 
                ? new HtmlString(encodedText) 
                : new HtmlString($"{encodedText[..(contextLength * 2)]}...");
        }

        // 计算截断边界
        var startPos = Math.Max(0, matchResult.Index - contextLength);
        var endPos = Math.Min(encodedText.Length, matchResult.Index + matchResult.Length + contextLength);
        var summaryContent = encodedText.Substring(startPos, endPos - startPos);

        // 高亮替换匹配内容,保留原文本大小写
        var highlightedContent = Regex.Replace(summaryContent, Regex.Escape(encodedKeyword), 
            "<strong class=\"search-highlight\">$&</strong>", RegexOptions.IgnoreCase);

        // 补前后省略号
        if (startPos > 0) highlightedContent = $"...{highlightedContent}";
        if (endPos < encodedText.Length) highlightedContent = $"{highlightedContent}...";

        return new HtmlString(highlightedContent);
    }
}

2. Razor页面调用

直接在列表展示的位置调用扩展方法即可,示例:

@foreach (var item in Model.SearchResults)
{
    <div class="result-item">
        <h3>@item.Title</h3>
        <p class="summary">
            @item.FullContent.ToSearchSummary(Model.SearchKeyword)
        </p>
    </div>
}

3. 可选:自定义高亮样式

在全局样式中添加高亮规则,调整展示效果:

.search-highlight {
    color: #d32f2f;
    background-color: #ffebee;
    padding: 0 3px;
    border-radius: 2px;
    font-weight: bold;
}

扩展说明

  • 如果需要匹配多个搜索词,只需要把关键词按空格拆分后循环做替换即可
  • 调整contextLength参数即可控制搜索词前后展示的上下文长度
  • 代码中已经默认做了XSS防护,不需要额外处理原文本的HTML转义问题

内容的提问来源于stack exchange,提问作者Hossein Tasm

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 10:54:02