gpt4 book ai didi

c# - 如何将 HttpRequest 复制到另一个 Web 服务?

转载 作者:行者123 更新时间:2023-11-30 18:02:07 25 4
gpt4 key购买 nike

出于测试目的,我目前在同一台 PC 上安装了两个相同的 Web 服务。第一个服务收到的请求也应该转到第二个服务。我的意图是使用 HttpModule 来执行此操作。我在 application.BeginRequest 期间处理请求。

public void AsyncForwardRequest(HttpRequest request)
{
try
{
// Prepare web request...
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(WSaddress);

req.Credentials = CredentialCache.DefaultCredentials;
req.Headers.Add("SOAPAction", request.Headers["SOAPAction"]);
req.ContentType = request.Headers["Content-Type"];
req.Accept = request.Headers["Accept"];
req.Method = request.HttpMethod;

// Send the data.
long posStream = request.InputStream.Position;
long len = request.InputStream.Length;
byte[] buff = new byte[len];
request.InputStream.Seek(0, SeekOrigin.Begin);
if (len < int.MaxValue && request.InputStream.Read(buff, 0, (int)len) > 0)
{
using (Stream stm = req.GetRequestStream())
{
stm.Write(buff, 0, (int)len);
}

request.InputStream.Position = posStream;
DebugOutputStream(request.InputStream);
request.InputStream.Seek(0, SeekOrigin.Begin);

IAsyncResult result = (IAsyncResult)req.BeginGetResponse(new AsyncCallback(RespCallback), req);
}
}
catch (Exception ex)
{

App.Error2(String.Format("RequestDuplicatorModule - BeginRequest; ERROR begin request: {0}", ex.Message), ex);
}

private static void RespCallback(IAsyncResult asynchronousResult)
{
try
{
// State of request is asynchronous.
var req = (HttpWebRequest)asynchronousResult.AsyncState;
WebResponse resp = (HttpWebResponse)req.EndGetResponse(asynchronousResult);

Stream responseStream = resp.GetResponseStream();
System.IO.Stream stream = responseStream;
Byte[] arr = new Byte[1024 * 100];
stream.Read(arr, 0, 1024 * 100);
if (arr.Length > 0)
{
string body = (new ASCIIEncoding()).GetString(arr);
Debug.Print(body);
}
}
catch (WebException ex)
{
App.Error2(String.Format("RequestDuplicatorModule - BeginRequest; ERROR begin request: {0}", ex.Message), ex);
}

}

此 (HttpWebResponse)req.EndGetResponse(asynchronousResult) 抛出异常:500 Internal Server Error 并失败。原始请求顺利通过。

请求.InnerStream: ...

这与网络服务地址不同有什么关系吗?就我而言,它们是: http://localhost/WS/service.asmxhttp://localhost/WS_replicate/service.asmx

最佳答案

我至少会实现这个,以便能够读取状态为 500 的 httpwebrequest 的内容:

catch (WebException ex)
{
HttpWebResponse webResponse = (HttpWebResponse)ex.Response;
Stream dataStream = webResponse.GetResponseStream();

if (dataStream != null)
{
StreamReader reader = new StreamReader(dataStream);
response = reader.ReadToEnd();
}
}

虽然没有回答您的问题,但我建议使用一个简单的 amsx 来读取请求,并将请求发布到两个不同的 Web 服务。如果您需要一些代码,请告诉我。

其他优点是 asmx 将更容易为开发人员以及处理部署的人员提供支持。您可以添加配置选项以使实际 url 动态化。

关于c# - 如何将 HttpRequest 复制到另一个 Web 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8325679/

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