.NET 4.x Не работает прокси сервер - C#
Формулировка задачи:
Доброго времени суток, уважаемые гости этой страницы!
Есть код, который принимает HTTP запрос от клиента(читай: браузера) и должен перенаправить его дальше.
Мой код
Вывод программы:
Listening...
Got request for http://charter97.org
Ссылка на объект не указывает на экземпляр объекта
И всё.
Забыл сказать, что сниффер не видит исходящего запроса. Как исправить?
public static void HttpProxyActivity()
{
int localProxyPort = 17325;
HttpListener lproxy_s = new HttpListener();
lproxy_s.Prefixes.Add(string.Format("http://*:{0}/", localProxyPort));
ServicePointManager.DefaultConnectionLimit = 1000;
lproxy_s.Start();
try
{
while (true)
{
Thread.Sleep(0);
Console.WriteLine("Listening...");
var context = lproxy_s.GetContext();
var requestString = context.Request.RawUrl;
Console.WriteLine("Got request for " + requestString);
//requested site is not denied
if (!requestString.Contains(Dns.GetHostEntry("tut.by").AddressList[0].ToString()) && !requestString.Contains("tut"))
{
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestString);
request.AllowAutoRedirect = false;
request.KeepAlive = context.Request.KeepAlive;
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
request.Method = context.Request.HttpMethod;
request.ContentType = context.Request.ContentType;
var cookies = new CookieContainer();
cookies.Add(new Uri(requestString), context.Request.Cookies);
request.CookieContainer = cookies;
request.Timeout = 20000;
HttpWebResponse resp;
try
{
resp = (HttpWebResponse)request.GetResponse();
}
catch (WebException err)
{
resp = (HttpWebResponse)err.Response;
}
Stream stream = resp.GetResponseStream();
StreamReader sr_ = new StreamReader(stream, Encoding.GetEncoding(resp.CharacterSet));
string response_from_remote_server = sr_.ReadToEnd();
var rs = new RequestData(request, context);
if (request.Method != "GET")
{
var t = resp.GetResponseStream();
HttpListenerResponse response = context.Response;
response.ContentType = resp.ContentType;
byte[] buf = new byte[2048];
buf = System.Text.Encoding.UTF8.GetBytes(response_from_remote_server);
response.ContentLength64 = buf.Length;
using (Stream output = response.OutputStream)
{
output.Write(buf, 0, buf.Length);
}
}
else
{
var t = resp.GetResponseStream();
HttpListenerResponse response = context.Response;
response.ContentType = resp.ContentType;
byte[] buf = new byte[2048];
StreamReader sr = new StreamReader(t);
string l = sr.ReadToEnd();
response.ContentLength64 = l.Length;
using (Stream output = response.OutputStream)
{
output.Write(System.Text.Encoding.UTF8.GetBytes(l), 0, l.Length);
}
sr.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
else
{
try
{
var request = WebRequest.Create(requestString) as HttpWebRequest;
request.AllowAutoRedirect = false;
request.KeepAlive = context.Request.KeepAlive;
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
request.Method = context.Request.HttpMethod;
request.ContentType = context.Request.ContentType;
var cookies = new CookieContainer();
cookies.Add(new Uri(requestString), context.Request.Cookies);
request.CookieContainer = cookies;
request.Timeout = 20000;
var rs = new RequestData(request, context);
if (request.Method != "GET")
{
HttpListenerResponse response = context.Response;
string responseString = "<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL /404 was not found on this server.</p></body></html>";
response.ContentType = "text/html; charset=UTF-8";
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
using (Stream output = response.OutputStream)
{
output.Write(buffer, 0, buffer.Length);
}
}
else
{
IAsyncResult result = (IAsyncResult)request.BeginGetResponse(
new AsyncCallback(RespCallback), rs);
HttpListenerResponse response = context.Response;
string responseString = "<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL /404 was not found on this server.</p></body></html>";
response.ContentType = "text/html; charset=UTF-8";
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
using (Stream output = response.OutputStream)
{
output.Write(buffer, 0, buffer.Length);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Помогите, хоть кто-нибудь...
Решение задачи: «.NET 4.x Не работает прокси сервер»
textual
Листинг программы
resp = (HttpWebResponse)request.GetResponse();