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

含HTML标签的字符串插值代码在.Net5正常.Net6运行异常问题咨询

问题成因

  1. 首先确认代码笔误:你示例代码中第一行定义的变量名是subect(缺失字母j),但插值表达式中引用的是subject,如果实际代码存在该问题会引发编译错误,若为示例输入笔误可忽略该点。
  2. 核心触发原因是.NET 6 新增的默认插值字符串处理程序DefaultInterpolatedStringHandler的边缘Case缺陷:当插值字符串拆分多行书写,同时包含大量转义双引号(即示例中style属性内的\"写法)时,处理程序内部的字符偏移计数计算错误,最终导致插值变量前的固定文本被错位拼接。
  3. 该问题仅在.NET 6环境复现,是因为.NET 5及更早版本的插值字符串底层默认走string.Format逻辑,不存在该处理缺陷。

解决办法

  • 方案1:替换插值字符串写法,改用普通字符串拼接或string.Format实现,避开DefaultInterpolatedStringHandler的处理逻辑。
  • 方案2:使用.NET 6支持的原始字符串字面量编写HTML内容,无需转义双引号,可完全规避转义字符引发的计数错误,示例写法如下:
var subject = "Subject Example";
var test = """
<p><strong><span style="font-size: 20px;">{subject}</span></strong></p><p><span style="color: rgb(34, 34, 34); font-family: Arial, Helvetica, sans-serif; font-size: small; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; display: inline !important; float: none;">The following information is in beta testing and isn't meant for a live portfolio. Use this information for paper trading only until further notice.</span></p>
""";
  • 方案3:无需修改业务代码,在项目.csproj文件的PropertyGroup节点中添加以下配置,强制禁用默认插值字符串处理程序,回退到.NET 5的处理逻辑:
<DisableDefaultInterpolatedStringHandler>true</DisableDefaultInterpolatedStringHandler>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:06:03