页首Html代码

HttpListner

教程1

https://ironpdf.com/blog/net-help/httplistener-csharp/

教程2

 

https://zetcode.com/csharp/httplistener/

 补充:

https://stackoverflow.com/questions/7004616/how-to-use-httplistener-to-receive-http-post-which-contain-xml

 

https://stackoverflow.com/questions/8637856/httplistener-with-post-data

https://stackoverflow.com/questions/57624357/building-json-response-through-httplistener-in-c-sharp

一个Http简单类

 

    public class HttpInstance
    {
        private HttpListener listner = new HttpListener();
        public event Action<string> OnUserLogged;
        public void RunHttpServer()
        {
            var prefix = "http://*:54321/";
            listner.Prefixes.Add(prefix);
            listner.Start();
            while(listner.IsListening)
            {
                var context = listner.GetContext();
                ProcessRequest(context);
            }

        }

        private void ProcessRequest(HttpListenerContext context)
        {
            HttpListenerRequest request = context.Request;
            var body = new StreamReader(context.Request.InputStream).ReadToEnd();

            string path = request.Url?.LocalPath;

            //if(path!=@"/favicon.ico")
            //    OnUserLogged?.Invoke(path);
            OnUserLogged?.Invoke(body);
            HttpListenerResponse response = context.Response;
            OutputString(response, "HelloWorld");

        }
        private void OutputString(HttpListenerResponse response,string data)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(data);
            response.ContentLength64 = buffer.Length;
            response.ContentType = "text/plain";
            using (Stream output = response.OutputStream)
            {
                output.Write(buffer, 0, buffer.Length);
            }
            response.Close();
        }
    }

 

关键代码:

1.获取post的所有内容

var body = new StreamReader(context.Request.InputStream).ReadToEnd();
var body = new StreamReader(request.InputStream,request.ContentEncoding).ReadToEnd();

2.获取路径

string path = request.Url?.LocalPath;

 

如何使用该类

            Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
            HttpInstance http = new HttpInstance();
            http.OnUserLogged += (name) =>
              {
                  dispatcher.Invoke(() =>
                  {
                      this.Text = name;
                  });
              };
            Task.Run(() =>
            {
                http.RunHttpServer();
            });

 

posted @ 2024-09-03 20:36  noigel  阅读(7)  评论(0编辑  收藏  举报
js脚本