如何解决HttpListener与现有注册冲突
我创建了一个函数( ListenForjson ),其中使用HttpListener来获取请求并从/向特定地址发送响应。我在 ActionResult Index()中调用此函数,以便它可以在后台运行。但是,由于我是在Web应用程序的主页中调用它的,因此每当我单击“转到主页”按钮时,我都会收到错误消息
Failed to listen on prefix because it conficts with an existing registration on the machine
我了解它发生的原因,但我不知道如何阻止它发生。
public ActionResult Index()
{
Thread thread = new Thread(() => ListenForjson());
thread.Start();
return View();
}
public void ListenForjson()
{
string[] prefixes = new string[] { "https://localhost:44337/" };
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
HttpListener listener = new HttpListener();
foreach (string s in prefixes)
listener.Prefixes.Add(s);
listener.Start();
while (true)
{
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
//Get Body(Json)
System.IO.Stream body = request.InputStream;
System.Text.Encoding encoding = request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body,encoding);
string json = reader.ReadToEnd();
JsonObject = DeserializeJson(json);
HttpListenerResponse response = context.Response;
var responseJson = JsonSerialization("SERVICE");
byte[] buffer = new byte[] { };
response.ContentType = "Application/json";
buffer = Encoding.ASCII.GetBytes(responseJson);
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer,buffer.Length);
context.Response.Close();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。