问题描述
我使用的是 ASP.NET 5.我需要将 IHtmlContent 转换为 String
I am using ASP.NET 5. I need to convert IHtmlContent to String
IIHtmlContent
是 ASP.NET 5
Microsoft.AspNet.Html.Abstractions
命名空间的一部分,是 TagBuilder 的接口
实现
IIHtmlContent
is part of the ASP.NET 5
Microsoft.AspNet.Html.Abstractions
namespace and is an interface that TagBuilder
implements
简化我有以下方法
public static IHtmlContent GetContent()
{
return new HtmlString("<tag>blah</tag>");
}
当我引用它
string output = GetContent().ToString();
我得到以下 GetContent() 的输出
I get the following output for GetContent()
"Microsoft.AspNet.Mvc.Rendering.TagBuilder"
而不是
<tag>blah</tag>
我想要的
我也尝试过使用 StringBuilder
I also tried using StringBuilder
StringBuilder html = new StringBuilder();
html.Append(GetContent());
但它也附加了相同的命名空间而不是字符串值
but it also appends the same namespace and not the string value
我尝试将其转换为 TagBuilder
I tried to cast it to TagBuilder
TagBuilder content = (TagBuilder)GetContent();
但 TagBuilder 没有转换为字符串的方法
but TagBuilder doesn't have a method that converts to string
如何将 IHtmlContent 或 TagBuilder 转换为字符串?
How do I convert IHtmlContent or TagBuilder to a string?
推荐答案
如果您需要做的只是将内容输出为字符串,只需添加此方法并将您的 IHtmlContent 对象作为参数传递以获取字符串输出:
If all you need to do is output the contents as a string, just add this method and pass your IHtmlContent object as a parameter to get the string output:
public static string GetString(IHtmlContent content)
{
using (var writer = new System.IO.StringWriter())
{
content.WriteTo(writer, HtmlEncoder.Default);
return writer.ToString();
}
}
这篇关于在 C# 中将 IHtmlContent/TagBuilder 转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!