Net Core:如何在 C# 中将 TagBuilder 转换为字符串?

Net Core:如何在 C# 中将 TagBuilder 转换为字符串?

问题描述:

在 Net Core 中是否有将 Tagbuilder 转换为 String 的本机方法?这仅适用于 ASP Net 5.将 IHtmlContent/TagBuilder 转换为 C# 中的字符串

Is there a native way to convert Tagbuilder to String in Net Core? This only is for ASP Net 5. Convert IHtmlContent/TagBuilder to string in C#

将 TagBuilder 的值转换为字符串

Convert value of TagBuilder into a String

我认为微软在 Net Core 中有一个替代功能

I think Microsoft had a replacement function for this in Net Core

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

aspnetcore.

The same WriteTo method is available in aspnetcore.

您应该能够继续从创建相同的 GetString 方法中受益,因为 TagBuilder 继承自 IHtmlContent.

You should be able to continue to benefit from creating the same GetString method, as TagBuilder inherits from IHtmlContent.

public static class IHtmlContentExtensions
{
    public static string GetString(this Microsoft.AspNetCore.Html.IHtmlContent content)
    {
        using (var writer = new System.IO.StringWriter())
        {        
            content.WriteTo(writer, System.Text.Encodings.Web.HtmlEncoder.Default);
            return writer.ToString();
        }
    }
}

然后从您的代码中,您可以调用

Then from your code, you can just call

TagBuilder myTag = // ...
string tagAsText = myTag.GetString();