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

时间:2019-07-14 09:08:36

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

在Net Core中是否有将Tagbuilder转换为String的本机方法?这仅适用于ASP Net 5。Convert IHtmlContent/TagBuilder to string in C#

将TagBuilder的值转换为字符串

我认为Microsoft在Net Core中对此具有替代功能

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

1 个答案:

答案 0 :(得分:-1)

aspnetcore中提供了相同的WriteTo方法。

由于TagBuilder继承自IHtmlContent,因此您应该能够继续受益于创建相同的GetString方法。

例如:

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();
        }
    }
}

然后从您的代码中,您只需调用

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