c# - 在 C# 中将 IHtmlContent/TagBuilder 转换为字符串

标签 c# asp.net asp.net-core asp.net-core-mvc

我正在使用 ASP.NET 5。我需要将 IHtmlContent 转换为字符串

IIHtmlContentASP.NET 5 Microsoft.AspNet.Html.Abstractions 命名空间的一部分,并且是 TagBuilder 的接口(interface) 实现

简化我有以下方法

public static IHtmlContent GetContent()
{
    return new HtmlString("<tag>blah</tag>");
}

当我引用它的时候

string output = GetContent().ToString();

我得到 GetContent() 的以下输出

"Microsoft.AspNet.Mvc.Rendering.TagBuilder" 

而不是

<tag>blah</tag>

我想要的

我也尝试过使用 StringBuilder

StringBuilder html = new StringBuilder();
html.Append(GetContent());

但它也附加相同的命名空间而不是字符串值

我试图将它转换为 TagBuilder

TagBuilder content = (TagBuilder)GetContent();

但是TagBuilder没有转换成字符串的方法

如何将 IHtmlContent 或 TagBuilder 转换为字符串?

最佳答案

如果您需要做的只是将内容作为字符串输出,只需添加此方法并将您的 IHtmlContent 对象作为参数传递即可获取字符串输出:

public static string GetString(IHtmlContent content)
{
    using (var writer = new System.IO.StringWriter())
    {        
        content.WriteTo(writer, HtmlEncoder.Default);
        return writer.ToString();
    } 
}     

关于c# - 在 C# 中将 IHtmlContent/TagBuilder 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33667308/

相关文章:

c# - 区分 "Refresh Post"或 "Real Post Back"的最佳方法是什么

jquery - Google Maps API 3 存在问题

c# - Blazor 获取两个属性的验证消息

c# - Visual Studio 2010 Crystal 报告 wpf

c# - 在C++中定义一个需要在C#和C++中实现的接口(interface)

asp.net - IIS7 上的 "Error loading RadChart Image"

c# - ASP.NET 核心 Web API : Required parameter with conditions

.net - 如何通过 MSBuild 获取 .NET Core 应用程序的输出路径?

c# - 通过查看每个对象自己的路径对多个对象集合进行排序

c# - 系统.OutOfMemoryException : Exception of type 'System.OutOfMemoryException' was thrown in angularjs