本文介绍了Net Core:如何在C#中将TagBuilder转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Net Core中是否有将Tagbuilder转换为String的本机方法?这仅适用于ASP Net5。

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

我认为Microsoft为此提供了替换功能在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();
    } 
}     


推荐答案

在WriteTo 方法。 writeto?view = aspnetcore-2.2 rel = nofollow noreferrer> 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();

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

09-22 05:18