gpt4 book ai didi

c# - 如何使用自定义 IHttpModule 和 HttpRequest 过滤器修改 POST 请求?

转载 作者:太空狗 更新时间:2023-10-30 00:58:14 24 4
gpt4 key购买 nike

概览

我希望能够修改第 3 方 Web 服务 (ArcGIS Server) 的请求参数和内容。这将用于创建存在于任何客户端应用程序和服务器应用程序之间的安全层。

我认为我已经找到了解决方案,但我目前在实现过程中遇到了一些困难。

可能的解决方案:使用自定义请求过滤器修改请求

对于解决方案,我松散地基于 sample shown on MSDN 实现了自定义请求过滤器.我已经“增强”了代码,以便我可以使用正则表达式搜索和替换必要的内容。这涉及:

  1. 将内容(存储在字节数组中)转换为字符串。
  2. 搜索字符串并执行任何必要的修改。
  3. 将修改后的字符串转换为字节数组并写入缓冲区。

示例如下:

public override int Read(byte[] buffer, int offset, int count)
{
int bytesRead = _stream.Read(buffer, offset, count);

string orgContent = Encoding.UTF8.GetString(buffer, offset, bytesRead);
string orgContentDecoded = HttpUtility.UrlDecode(orgContent);

string layersPattern = @"&layers=(show|hide|include|exclude):([0-9]+,?)+";
Regex layersRegex = new Regex(layersPattern, RegexOptions.IgnoreCase);

string[] permittedLayers = new string[] { "0" , "1" };
string replacementLayers = "&layers=show:" + String.Join(",", permittedLayers);
string newContentDecoded = layersRegex.Replace(orgContentDecoded, replacementLayers);

string newContent = newContentDecoded.Replace(",", "%2C").Replace(":", "%3A");

byte[] newBuffer = Encoding.UTF8.GetBytes(newContent);
int newByteCountLength = Encoding.UTF8.GetByteCount(newContent);

Encoding.UTF8.GetBytes(newContent, 0, Encoding.UTF8.GetByteCount(newContent), buffer, 0);

return bytesRead;
}

只要修改后的内容长度原始内容长度没有区别,这似乎就可以正常工作。例如,如果我用 2 替换 1 一切正常。但是,如果我将 1 替换为 10(从而将消息大小增加 1),则会收到来自 ArcGIS Server 的错误消息,指出该格式不受支持。

这让我注意到两个问题:

  1. 当前的实现不处理分块请求。也就是说,如果请求 sie 足够大,Read 可能会为单个请求调用多次。 在这种情况下应该如何处理分块?
  2. 错误消息的根本原因是什么?问题是否与内容长度与流长度不同有关? 如何正确修改内容,以便更改其长度不是问题?

有什么想法吗?

最佳答案

这个问题第二部分的答案是返回修改后的内容大小,而不是原始流的大小。看哪!

// return bytesRead;
return newByteCountLength;

关于c# - 如何使用自定义 IHttpModule 和 HttpRequest 过滤器修改 POST 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3240170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com