asp.net request.filter 覆盖 stream.read

asp.net request.filter override stream.read

我想更改请求内容,即我想将中文繁体转换为中文简体,它们是1:1映射。我使用以下代码:

Global.asax:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    Request.Filter = new RequestFilter(Request.Filter);
}

HttpRequest.filter的用法在这里:msdn

请求过滤器:

public override int Read(byte[] buffer, int offset, int count)
{
    // the length of buffer is 8192, will truncate my request stream 
    int len = _sink.Read(buffer, offset, count);
    if (len == 0)
    {
        Array.Clear(buffer, 0, count);
        return len;
    }


    System.Text.Encoding curEncoding = HttpContext.Current.Request.ContentEncoding;
    string strBuffer = curEncoding.GetString(buffer);

    Regex regQuery = new Regex(@"=([^&]+)", RegexOptions.Compiled);

    strBuffer = regQuery.Replace(strBuffer, new MatchEvaluator((match) =>
    {
        string val = HttpContext.Current.Server.UrlDecode(match.Groups[1].ToString());

        return "=" + HttpContext.Current.Server.UrlEncode(ChineseConverter.Convert(val, 
            ChineseConversionDirection.TraditionalToSimplified));
    }));

    Array.Clear(buffer, 0, count);
    byte[] newBuff = curEncoding.GetBytes(strBuffer);
    newBuff.CopyTo(buffer, 0);

    return len;
}

我在 Stream class 上覆盖了方法 Read,但是第一个参数 byte[] buffer 默认长度为 8192,会截断我的内容。

eg: encodeURI('中') is '%E4%B8%AD', may be only '%E4' at the end of byte[] buffer

如何获取第一个参数byte[]缓冲区中的所有内容,或者谁能告诉我一些获取它的技巧。

任何时候您想要使用过滤器修改请求(或响应)中数据的长度,您都需要使用缓冲技术。我发布了一个示例项目,它使用 HttpModule 演示了这种缓冲过滤技术。

https://github.com/snives/HttpModuleRewrite