El *_*Che 38 .net c# communication forwarding http
我有一个Web应用程序,它在两个不同的Web应用程序之间进行通信(一个接收者和一个发送者,发送者与我的应用程序通信,我的应用程序与两者通信).
常规方案是发件人向我的应用程序发送HttpRequest,然后我在HttpHandler中收到它.这反过来将HttpContext发送到一些businesslogic来做一些管道.
在我的业务类完成存储数据(一些日志记录等)后,我想将所有头,表单数据等的相同请求中继到接收器应用程序.这必须从类发送,而不是HttpHandler.
问题是 - 我如何获取HttpContext对象,转发/转发完全相同的请求,只修改从http://myserver.com/到http://receiver.com的URL .
优选的c#中的任何代码示例都会很棒!
dia*_*lic 37
我有一个扩展方法HttpResponseBase来将传入请求复制到传出请求.
用法:
var externalRequest = (HttpWebRequest)WebRequest.Create("http://stackoverflow.com");
this.Request.CopyTo(externalRequest);
var externalResponse = (HttpWebResponse)externalRequest.GetResponse();
Run Code Online (Sandbox Code Playgroud)
资源:
/// <summary>
/// Copies all headers and content (except the URL) from an incoming to an outgoing
/// request.
/// </summary>
/// <param name="source">The request to copy from</param>
/// <param name="destination">The request to copy to</param>
public static void CopyTo(this HttpRequestBase source, HttpWebRequest destination)
{
destination.Method = source.HttpMethod;
// Copy unrestricted headers (including cookies, if any)
foreach (var headerKey in source.Headers.AllKeys)
{
switch (headerKey)
{
case "Connection":
case "Content-Length":
case "Date":
case "Expect":
case "Host":
case "If-Modified-Since":
case "Range":
case "Transfer-Encoding":
case "Proxy-Connection":
// Let IIS handle these
break;
case "Accept":
case "Content-Type":
case "Referer":
case "User-Agent":
// Restricted - copied below
break;
default:
destination.Headers[headerKey] = source.Headers[headerKey];
break;
}
}
// Copy restricted headers
if (source.AcceptTypes.Any())
{
destination.Accept = string.Join(",", source.AcceptTypes);
}
destination.ContentType = source.ContentType;
destination.Referer = source.UrlReferrer.AbsoluteUri;
destination.UserAgent = source.UserAgent;
// Copy content (if content body is allowed)
if (source.HttpMethod != "GET"
&& source.HttpMethod != "HEAD"
&& source.ContentLength > 0)
{
var destinationStream = destination.GetRequestStream();
source.InputStream.CopyTo(destinationStream);
destinationStream.Close();
}
}
Run Code Online (Sandbox Code Playgroud)
El *_*Che 26
实际上,这样的事情运作良好
HttpRequest original = context.Request;
HttpWebRequest newRequest = (HttpWebRequest)WebRequest.Create(newUrl);
newRequest .ContentType = original.ContentType;
newRequest .Method = original.HttpMethod;
newRequest .UserAgent = original.UserAgent;
byte[] originalStream = ReadToByteArray(original.InputStream, 1024);
Stream reqStream = newRequest .GetRequestStream();
reqStream.Write(originalStream, 0, originalStream.Length);
reqStream.Close();
newRequest .GetResponse();
Run Code Online (Sandbox Code Playgroud)
编辑:ReadToByteArray方法只是从流中生成一个字节数组
| 归档时间: |
|
| 查看次数: |
31054 次 |
| 最近记录: |