含HTML标签的字符串插值代码在.Net5正常.Net6运行异常问题咨询
问题成因
- 首先确认代码笔误:你示例代码中第一行定义的变量名是
subect(缺失字母j),但插值表达式中引用的是subject,如果实际代码存在该问题会引发编译错误,若为示例输入笔误可忽略该点。 - 核心触发原因是.NET 6 新增的默认插值字符串处理程序
DefaultInterpolatedStringHandler的边缘Case缺陷:当插值字符串拆分多行书写,同时包含大量转义双引号(即示例中style属性内的\"写法)时,处理程序内部的字符偏移计数计算错误,最终导致插值变量前的固定文本被错位拼接。 - 该问题仅在.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
相关产品推荐
相关产品推荐

