我有一个Web应用程序,它在两个不同的Web应用程序之间进行通信(一个接收者和一个发送者,发送者与我的应用程序通信,我的应用程序与两者通信).
常规方案是发件人向我的应用程序发送HttpRequest,然后我在HttpHandler中收到它.这反过来将HttpContext发送到一些businesslogic来做一些管道.
在我的业务类完成存储数据(一些日志记录等)后,我想将所有头,表单数据等的相同请求中继到接收器应用程序.这必须从类发送,而不是HttpHandler.
问题是 - 我如何获取HttpContext对象,转发/转发完全相同的请求,只修改从http://myserver.com/到http://receiver.com的URL .
优选的c#中的任何代码示例都会很棒!
我有一个扩展方法HttpResponseBase
来将传入请求复制到传出请求.
用法:
var externalRequest = (HttpWebRequest)WebRequest.Create("http://stackoverflow.com"); this.Request.CopyTo(externalRequest); var externalResponse = (HttpWebResponse)externalRequest.GetResponse();
资源:
////// Copies all headers and content (except the URL) from an incoming to an outgoing /// request. /// /// The request to copy from /// The request to copy to 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(); } }
实际上,这样的事情运作良好
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();
编辑:ReadToByteArray方法只是从流中生成一个字节数组