本文介绍了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();
    } 
}     

推荐答案

.

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

这篇关于Net Core:如何在 C# 中将 TagBuilder 转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 05:18