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

ASP.NET Core 2.1中如何将对象实际内容写入文本文件?

解决ASP.NET Core 2.1中对象内容写入文件仅显示类型名的问题

针对你遇到的三个对象,分别处理如下:

1. 处理List<Claim>集合

直接输出集合会调用默认ToString()返回类型名,需要遍历集合中的每个Claim对象,输出其关键属性:

w.WriteLine("=== Claim列表 ===");
foreach (var claim in saml2AuthnResponse.ClaimsIdentity.Claims)
{
    w.WriteLine($"类型: {claim.Type}, 值: {claim.Value}");
}
w.WriteLine("\n");

2. 处理ClaimsIdentity对象

ClaimsIdentity.ToString()默认仅返回类型名,需要手动提取其核心信息:

w.WriteLine("=== ClaimsIdentity信息 ===");
w.WriteLine($"认证类型: {saml2AuthnResponse.ClaimsIdentity.AuthenticationType}");
w.WriteLine($"名称: {saml2AuthnResponse.ClaimsIdentity.Name}");
w.WriteLine("包含的Claim:");
foreach (var claim in saml2AuthnResponse.ClaimsIdentity.Claims)
{
    w.WriteLine($"  - {claim.Type}: {claim.Value}");
}
w.WriteLine("\n");

3. 处理XmlDocument对象

XmlDocument直接输出会返回类型名,需要使用格式化方式输出XML内容:

w.WriteLine("=== SAML响应XML ===");
var stringWriter = new StringWriter();
var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true });
saml2AuthnResponse.ToXml().WriteTo(xmlWriter);
xmlWriter.Flush();
w.WriteLine(stringWriter.ToString());
w.WriteLine("\n");

完整修改后的写入代码

string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "data.txt");

using (StreamWriter w = new StreamWriter(filePath, true))
{
    w.WriteLine("\n");
    w.WriteLine("testing...\n");
    
    // 输出Claim列表
    w.WriteLine("=== Claim列表 ===");
    foreach (var claim in saml2AuthnResponse.ClaimsIdentity.Claims)
    {
        w.WriteLine($"类型: {claim.Type}, 值: {claim.Value}");
    }
    w.WriteLine("\n");
    
    // 输出ClaimsIdentity信息
    w.WriteLine("=== ClaimsIdentity信息 ===");
    w.WriteLine($"认证类型: {saml2AuthnResponse.ClaimsIdentity.AuthenticationType}");
    w.WriteLine($"名称: {saml2AuthnResponse.ClaimsIdentity.Name}");
    w.WriteLine("包含的Claim:");
    foreach (var claim in saml2AuthnResponse.ClaimsIdentity.Claims)
    {
        w.WriteLine($"  - {claim.Type}: {claim.Value}");
    }
    w.WriteLine("\n");
    
    // 输出格式化后的XML
    w.WriteLine("=== SAML响应XML ===");
    var stringWriter = new StringWriter();
    var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true });
    saml2AuthnResponse.ToXml().WriteTo(xmlWriter);
    xmlWriter.Flush();
    w.WriteLine(stringWriter.ToString());
}

核心原因

.NET中大部分复杂对象(集合、自定义类、XmlDocument等)的默认ToString()方法仅返回对象的类型名称,而非内部内容。需要手动提取对象的属性或调用特定方法(如XmlDocument的格式化输出逻辑)来获取可读内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 20:55:02