【问题标题】:Convert IHtmlContent/TagBuilder to string in C#在 C# 中将 IHtmlContent/TagBuilder 转换为字符串
【发布时间】:2015-11-12 08:41:05
【问题描述】:

我使用的是 ASP.NET 5。我需要将 IHtmlContent 转换为字符串

IIHtmlContentASP.NET 5 Microsoft.AspNet.Html.Abstractions 命名空间的一部分,是TagBuilder 实现的接口

简化我有以下方法

public static IHtmlContent GetContent()
{
    return new HtmlString("<tag>blah</tag>");
}

当我引用它时

string output = GetContent().ToString();

GetContent() 得到以下输出

"Microsoft.AspNet.Mvc.Rendering.TagBuilder" 

而不是

<tag>blah</tag>

我想要的

我也尝试过使用 StringBuilder

StringBuilder html = new StringBuilder();
html.Append(GetContent());

但它也附加了相同的命名空间,而不是字符串值

我尝试将其转换为 TagBuilder

TagBuilder content = (TagBuilder)GetContent();

但是 TagBuilder 没有转换为字符串的方法

如何将 IHtmlContent 或 TagBuilder 转换为字符串?

【问题讨论】:

  • ToHtmlString 呢?另外,你从哪里得到IHtmlContent
  • 我指的是HtmlString类的方法。你能告诉我IHtmlContent 的文档吗?它似乎不在 MSDN 上

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


【解决方案1】:

如果您只需要将内容输出为字符串,只需添加此方法并将您的 IHtmlContent 对象作为参数传递即可获取字符串输出:

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

【讨论】:

  • 好答案..这就是我要找的。​​span>
  • 不适用于 asp.vnext 核心。改用HtmlEncoder.Default
  • 不应该将StringWriter 包裹在using 块中吗?
  • @bradlis7 你是对的。我已更新解决方案以反映您的建议。
  • 在 Core 中使用 Razor,您可以简单地使用 @tagBuilderInstance。它将构建并写入结果。
【解决方案2】:

添加到上面的答案:

HtmlEncoder 的新实例在 ASP.NET Core RTM 中不起作用,因为删除了 Microsoft.Extensions.WebEncoders 命名空间,并且新的 HtmlEncoder 类被移动到了新的命名空间 System.Text.Encodings.Web,但是这个类是现在写成一个抽象和密封的类,所以你不能从它创建一个新的实例或派生类。

HtmlEncoder.Default 传递给该方法,它将起作用

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

【讨论】:

    【解决方案3】:

    ASP.NET Core 实际上引入了一些精心的优化。如果您正在构建 HTML 扩展方法,那么最有效的方法是避免使用字符串:

    public static IHtmlContent GetContent(this IHtmlHelper helper)
    {
        var content = new HtmlContentBuilder()
                         .AppendHtml("<ol class='content-body'><li>")
                         .AppendHtml(helper.ActionLink("Home", "Index", "Home"))
                         .AppendHtml("</li>");
    
        if(SomeCondition())
        {
            content.AppendHtml(@"<div>
                Note `HtmlContentBuilder.AppendHtml()` is Mutable
                as well as Fluent/Chainable.
            </div>");
        }
    
        return content;
    }
    

    最后在 razor 视图中,我们甚至不再需要 @Html.Raw(Html.GetContent())(过去在 ASP.NET MVC 5 中需要) -根据 Lukáš Kmoch 评论无效下面:ASP.NET MVC 5 has type MvcHtmlString. You don't need to use Html.Raw()

    只需致电@Html.GetContent() 就足够了,Razor 将处理所有逃跑的业务。

    【讨论】:

    • 我喜欢服务器端渲染的原因是它以牺牲性能为代价编写无聊的标记要快得多。为什么我们要在标记中注入一个有序列表,以便我们可以渲染和锚定标签?这对SEO不利,并增加了开发时间。哎呀
    • ASP.NET MVC 5 的类型为 MvcHtmlString。你不需要使用 Html.Raw()
    【解决方案4】:

    有一个示例: https://github.com/aspnet/Mvc/blob/release/2.2/test/Microsoft.AspNetCore.Mvc.Views.TestCommon/HtmlContentUtilities.cs

    public static string HtmlContentToString(IHtmlContent content, HtmlEncoder encoder = null)
            {
                if (encoder == null)
                {
                    encoder = new HtmlTestEncoder();
                }
    
                using (var writer = new StringWriter())
                {
                    content.WriteTo(writer, encoder);
                    return writer.ToString();
                }
            }
    

    【讨论】:

      【解决方案5】:

      这是一个扩展方法,因此您可以像 ToString() 一样使用它。

          public static string ToHtmlString(this IHtmlContent content)
          {
              if (content is HtmlString htmlString)
              {
                  return htmlString.Value;
              }
      
              using (var writer = new StringWriter())
              {
                  content.WriteTo(writer, HtmlEncoder.Default);
                  return writer.ToString();
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2021-05-05
        • 1970-01-01
        • 1970-01-01
        • 2014-05-02
        • 2020-02-20
        • 2023-03-28
        • 1970-01-01
        • 2011-02-03
        • 1970-01-01
        相关资源
        最近更新 更多