Net Core: How to Convert TagBuilder to String in C#?

给你一囗甜甜゛ 提交于 2019-12-11 15:26:08

问题


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#

Convert value of TagBuilder into a String

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

回答1:


The same WriteTo method is available in aspnetcore.

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

For example:

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


来源:https://stackoverflow.com/questions/57025984/net-core-how-to-convert-tagbuilder-to-string-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!