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 (将#修改为@)