.net 4 xslt转换扩展功能坏了

pet*_*ter 2 .net c# asp.net xslt .net-4.0

我正在升级asp.net v3.5网络应用程序.到v4,我在XmlDataSource对象上使用的XSLT转换遇到了一些问题.

XSLT文件的一部分:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:HttpUtility="ds:HttpUtility">
  <xsl:output method="xml" indent="yes" encoding="utf-8"/>
  <xsl:template match="/Menus">
    <MenuItems>
      <xsl:call-template name="MenuListing" />
    </MenuItems>
  </xsl:template>

  <xsl:template name="MenuListing">
    <xsl:apply-templates select="Menu" />
  </xsl:template>

  <xsl:template match="Menu">
      <MenuItem>
        <xsl:attribute name="Text">
          <xsl:value-of select="HttpUtility:HtmlEncode(MenuTitle)"/>
        </xsl:attribute>
        <xsl:attribute name="ToolTip">
          <xsl:value-of select="MenuTitle"/>
        </xsl:attribute>
      </MenuItem>
  </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

问题似乎就在于此

<xsl:value-of select="HttpUtility:HtmlEncode(MenuTitle)"/>
Run Code Online (Sandbox Code Playgroud)

删除它并用普通文本替换它,它将工作.我设置XML数据源的方式:

    xmlDataSource.TransformArgumentList.AddExtensionObject("ds:HttpUtility", new System.Web.HttpUtility());
    xmlDataSource.Data = Cache.FetchPageMenu();
Run Code Online (Sandbox Code Playgroud)

我一直在微软页面上搜索v4的任何变化,但找不到任何变化.所有这些在v3.5(以及v2之前)中运行良好.没有收到任何错误,数据只是没有显示.

Dir*_*mar 5

问题似乎是.NET 4.0引入了额外的重载HttpUtility.HtmlEncode.高达.NET 3.5,存在以下重载:

public static string HtmlEncode(string s);
public static void HtmlEncode(string s, TextWriter output);
Run Code Online (Sandbox Code Playgroud)

.NET 4.0还有以下方法:

public static string HtmlEncode(object value);
Run Code Online (Sandbox Code Playgroud)

这导致XslTransformException:

(不明确的方法调用.扩展对象'ds:HttpUtility'包含多个'HtmlEncode'方法,它们有1个参数.

您可能没有看到异常,因为它被捕获到某个地方而没有立即报告.

使用.NET Framework类作为扩展对象是一件脆弱的事情,因为新的Framework版本可能会破坏您的转换.

修复方法是创建自定义包装类并将其用作扩展对象.此包装类可能没有具有相同数量参数的重载:

class ExtensionObject
{
    public string HtmlEncode(string input)
    {
        return System.Web.HttpUtility.HtmlEncode(input);
    }
}

//...
XsltArgumentList arguments = new XsltArgumentList();
arguments.AddExtensionObject("my:HttpUtility", new ExtensionObject());
Run Code Online (Sandbox Code Playgroud)