使用HttpEncoder进行自定义URL编码

本文关键字:URL 编码 自定义 HttpEncoder 使用 | 更新日期: 2023-09-27 18:25:51

我正在尝试覆盖自定义HttpEncoder类中HTML和URL的默认编码。该类已在web.config文件中注册,对于HTML编码似乎可以正常工作,但从未调用用于编码URL的重写方法。浏览一下.NET源代码,它看起来应该是,但也许我遗漏了一些东西。

我的编码器看起来像:

namespace MyProject
{
    public class CustomHttpEncoder : HttpEncoder
    {
        protected override void HtmlEncode(string value, TextWriter output)
        {
            base.HtmlEncode(value, output);
        }
        protected override void HtmlAttributeEncode(string value, TextWriter output)
        {
            base.HtmlAttributeEncode(value, output);
        }
        protected override string UrlPathEncode(string value)
        {
            return base.UrlPathEncode(value);
        }
        protected override byte[] UrlEncode(byte[] bytes, int offset, int count)
        {
            return base.UrlEncode(bytes, offset, count);
        }
    }
}

在我使用的剃须刀页面中:

@Html.ActionLink("Title", "action", "controller", new { urlParam = "a spaced param" }, null)

编码器在web.config中注册为:

<httpRuntime encoderType="MyProject.CustomHttpEncoder" />

CustomHttpEncoder类的HtmlEncode()HtmlAttributeEncode()方法中设置断点效果非常好。我可以通过编码器看到页面的所有不同部分,包括我的链接标题。

但是,从链接(/controller/action/a%20spaced%20param)生成的URL从未在UrlPathEncode()UrlEncode()上通过我的编码器运行。它显然是在某个地方编码的,但在哪里?

文档和我所有的谷歌搜索都表明这应该有效,因为几乎所有的东西都是通过注册的HttpEncoderHttpUtility类运行的。

我应该注意的是,这只是我尝试截取URL编码的一个例子,我并没有试图在URL编码的某些变体中用"+"替换空格。我希望能够截获编码中的任何模式。

使用HttpEncoder进行自定义URL编码

您必须在web.config中注册类型(CustomHttpEncoder)。

    <system.web>
        <httpRuntime encoderType="CustomHttpEncoder, AssemblyName"/>
    </system.web>

请注意,您需要将AssemblyName替换为程序集的实际名称。如果将编码器放在命名空间中,则需要确保提供完全限定的类型名。