『QQ:1353814576』

.NET5框架下使用HttpListener类实现http接口监听替代OWIN自我寄宿


场景:

下面就是HttpListener类实现http接口的核心代码 需要的同学可以参考下

        static HttpListener _HttpListener;

        public static bool Start(out string error)
        {
            error = "";
            if (!HttpListener.IsSupported)
            {
                //系统不支持
                return false;
            }

            try
            {
                _HttpListener = new HttpListener();
                string host1 = $"http://127.0.0.1:8888/";
                string host2 = $"http://本地ip:8888/";
                _HttpListener.Prefixes.Add(host1);
                _HttpListener.Prefixes.Add(host2);
                _HttpListener.Start();

                Task.Factory.StartNew(async () =>
                {
                    //这里使用的while循环去监听消息。其实还有一种BeginGetContext的方式去监听消息 但感觉还没这个干净代码量还要多一些就懒得换了,有兴趣的同学百度找一下
                    while (_HttpListener.IsListening)
                    {
                        HttpListenerContext context = _HttpListener.GetContext();
                        //context 就和一般的.net mvc web项目里控制器里的httpcontext 类似 这里就不细说了
                        await Task.Run(() =>
                        {
                           //输出信息流
                           using (StreamWriter writer = new StreamWriter(response.OutputStream))
                           {
                                response.StatusCode = 200;
                                response.AddHeader("Content-Type", "application/json");
                                writer.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new                                         {success=true,message="执行成功"}));
                           }
                        });
                        await Task.Delay(1);
                    }
                });
                return true;
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return false;
            }
        }