2014-10-08 59 views
1

我想覆盖自定义HttpEncoder类中的HTML和URL的默认编码。该类在web.config文件中注册,似乎对HTML编码工作得很好,但不会调用用于编码URL的重写方法。通过.NET来源看起来应该是,但也许我错过了一些东西。使用HttpEncoder自定义URL编码

我的编码器是这样的:

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" /> 

设置中的HtmlEncode()HtmlAttributeEncode()方法中的断点班的作品很棒。我可以看到页面的各个位都通过编码器运行,包括链接的标题。

但是,链接(/controller/action/a%20spaced%20param)中生成的URL绝不会通过我的编码器在UrlPathEncode()UrlEncode()上运行。它显然被编码在某处,但在哪里?

文档和我所有的Google搜索都表明这应该可以工作,因为几乎所有的东西都可以通过注册HttpEncoder而不是HttpUtility类。

我应该注意到这只是我试图拦截URL编码的一个示例,我不想尝试在URL编码的某些变体中用"+"替换空格。我希望能够拦截编码中的任何模式。

+0

你需要展示如何在web.config中注册这个? – Liam 2014-10-08 08:22:10

+0

由于只有一种方法,它显然适用于HTML编码,我并不认为这是必要的,但我会编辑以包含它。 – 2014-10-08 08:23:39

回答

1

您必须在web.config中注册类型(CustomHttpEncoder)。 <system.web> <httpRuntime encoderType="CustomHttpEncoder, AssemblyName"/> </system.web>

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