我们在端口80上有一个使用HttpListener的项目。 它在生产和开发中完美地适用于.net 3.5。 出于依赖性原因,我们必须将其迁移到.net 4.5.1。该项目在开发中运行良好,但在我们投入Azure时则不行。
升级的另一部分是从IIS 7.5迁移到IIS 8。
该应用程序的主要代码。首先是基础监听器:
public abstract class BaseHttpListener
{
private IPEndPoint HttpEndPoint;
private IPEndPoint HttpsEndPoint;
private HttpListener Listener;
protected BaseHttpListener(IPEndPoint http, IPEndPoint https = null)
{
HttpEndPoint = http;
HttpsEndPoint = https;
}
public void Start()
{
var thread = new System.Threading.Thread(new System.Threading.ThreadStart(Listen));
thread.Start();
}
private void Listen()
{
// Create a HTTP listener.
Listener = new System.Net.HttpListener();
Listener.Prefixes.Add(String.Format("http://{0}/", HttpEndPoint));
if (HttpsEndPoint != null)
{
Listener.Prefixes.Add(String.Format("https://{0}/", HttpsEndPoint));
}
Listener.Start();
while (Listener.IsListening)
{
var context = Listener.BeginGetContext(ListenerCallback, Listener);
context.AsyncWaitHandle.WaitOne();
}
}
private void ListenerCallback(IAsyncResult ar)
{
var httpListener = ar.AsyncState as HttpListener;
if (httpListener.IsListening == false)
return;
var context = httpListener.EndGetContext(ar);
try
{
Process(context);
}
catch (Exception exception)
{
LogManager.Instance.Fatal(exception, String.Concat("Fatal exception occurs when try to process '", context.Request.Url.ToString(), "'"));
//We should try to send a error to the client
context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
context.Response.StatusDescription = System.Net.HttpStatusCode.InternalServerError.ToString();
context.Response.Close();
}
}
protected abstract void Process(HttpListenerContext context);
public void Stop()
{
Listener.Prefixes.Clear();
Listener.Close();
}
简单的索引处理程序:
public class IndexRequestHandler : RequestHandler
{
public IndexRequestHandler(String handledPath)
: base(handledPath)
{
}
public override void HandleRequest(System.Net.HttpListenerContext context)
{
var html = @"<!doctype html>
<html lang='en>'
<head>
<meta charset='utf-8'>
<title>It's ready</title>
</head>
<body>
<h1>It's ready</h1>
</body>
</html>";
var bytes = System.Text.Encoding.UTF8.GetBytes(html);
context.Response.ContentLength64 = bytes.LongLength;
context.Response.ContentType = "text/html;charset=UTF-8";
try
{
context.Response.OutputStream.Write(bytes, 0, bytes.Length);
context.Response.Close();
}
catch (Exception ex)
{
LogManager.Instance.Error(ex, "IndexRequestHandler.HandleRequest");
}
}
}
如果需要,我可以给你其他例子。
另一个重要的事情是我运行一个cmd命令:telnet X.X.X.X 80它返回给我一些但是当我在chrome中测试http://X.X.X.X时,我什么都没得到
感谢您的帮助!