少有人走的路

勇哥的工业自动化技术网站

web技术学习(13)web界面和C#进行通讯方法-- HttpListener REST

C# 控制台 + HttpListener(原生 HTTP 短接口,零 NuGet)

属于普通 HTTP 请求(REST 风格),一问一答,短连接。


mtvservices.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>disable</Nullable>
    <ImplicitUsings>disable</ImplicitUsings>
  </PropertyGroup>

</Project>


mtvservices.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.Json;

namespace MtvServer
{
    // ===================== Model 层:数据结构 =====================
    public class Song
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Singer { get; set; }
    }

    // 统一的 API 返回格式,网页端好判断
    public class ApiResult
    {
        public bool Ok { get; set; }
        public string Message { get; set; }
        public object Data { get; set; }

        public static ApiResult Success(object data = null, string msg = "")
            => new ApiResult { Ok = true, Data = data, Message = msg };
        public static ApiResult Fail(string msg)
            => new ApiResult { Ok = false, Message = msg };
    }

    // ===================== Service 层:业务逻辑(留空待填)=====================
    public class SongService
    {
        // TODO: 以后在这里实现:扫描音乐目录 / 歌单管理 / 播放控制 / 搜索……
        public List<Song> GetAll()
        {
            //return new List<Song>();   // 暂时空数据
            return new List<Song>
            {
                new Song { Id = 1, Name = "起风了", Singer = "买辣椒也用券" },
                new Song { Id = 2, Name = "稻香",   Singer = "周杰伦" },
            };
        }
    }

    // ===================== HTTP 层:服务器骨架 =====================
    public static class Program
    {
        const int Port = 8088;
        static readonly SongService Service = new SongService();

        // mtv.html 在项目根目录(BaseDirectory = bin/Debug/net8.0/,向上 3 级)
        static readonly string HtmlPath =
            Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "mtv.html"));

        static void Main()
        {
            Console.WriteLine("页面路径: " + HtmlPath
                + (File.Exists(HtmlPath) ? "  [OK]" : "  [!] 找不到,请调整 HtmlPath"));

            var listener = new HttpListener();
            listener.Prefixes.Add($"http://localhost:{Port}/");
            try { listener.Start(); }
            catch (HttpListenerException ex)
            {
                Console.WriteLine("启动失败(端口被占用?):" + ex.Message);
                return;
            }
            Console.WriteLine($"服务已启动 → 浏览器打开 http://localhost:{Port}/mtv.html");
            Console.WriteLine("按 Ctrl+C 退出\n");

            while (true)
            {
                var ctx = listener.GetContext();          // 阻塞等待下一个请求
                try { Handle(ctx); }
                catch (Exception ex)
                {
                    Console.WriteLine("[错误] " + ex.Message);
                    try { SendJson(ctx.Response, 500, ApiResult.Fail(ex.Message)); } catch { }
                }
            }
        }

        // ---------- 路由分发:以后新功能就往这里加 case ----------
        static void Handle(HttpListenerContext ctx)
        {
            var req = ctx.Request;
            var res = ctx.Response;
            string path = req.Url.AbsolutePath;
            Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] {req.HttpMethod} {path}");

            if (req.HttpMethod == "OPTIONS")            // CORS 预检,直接放行
            {
                SendJson(res, 200, ApiResult.Success());
                return;
            }

            switch (path)
            {
                case "/":
                case "/mtv.html":                       // 托管页面
                    SendFile(res, HtmlPath, "text/html");
                    break;

                case "/api/songs":                      // GET 歌曲列表
                    SendJson(res, 200, ApiResult.Success(Service.GetAll()));
                    break;

                case "/api/songs/search":               // GET 搜索 /api/songs/search?kw=xx
                    {
                        string kw = req.QueryString["kw"] ?? "";
                        // TODO: 改成 Service.Search(kw)
                        SendJson(res, 200, ApiResult.Success(Service.GetAll()));
                        break;
                    }

                case "/api/command":                    // POST 网页→C# 的命令通道
                    {
                        string body = ReadBody(req);
                        Console.WriteLine("收到网页命令: " + body);
                        // TODO: 解析 JSON 并执行真实命令,例如 { "cmd": "play", "id": 3 }
                        SendJson(res, 200, ApiResult.Success(null, "已收到"));
                        break;
                    }

                default:
                    SendJson(res, 404, ApiResult.Fail("未知接口: " + path));
                    break;
            }
        }

        // ---------- 工具方法 ----------
        static string ReadBody(HttpListenerRequest req)
        {
            using (var reader = new StreamReader(req.InputStream, Encoding.UTF8))
                return reader.ReadToEnd();
        }
        // 统一 JSON 命名策略:C# 属性 Ok/Message/Data → 输出 ok/message/data,与网页端约定一致
        static readonly JsonSerializerOptions JsonOpts = new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
        };

        static void SendJson(HttpListenerResponse res, int status, object data)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(data, JsonOpts));
            res.StatusCode = status;
            res.ContentType = "application/json; charset=utf-8";
            res.Headers.Add("Access-Control-Allow-Origin", "*");
            res.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
            res.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
            res.ContentLength64 = bytes.Length;
            res.OutputStream.Write(bytes, 0, bytes.Length);
            res.OutputStream.Close();
        }

        static void SendFile(HttpListenerResponse res, string path, string mime)
        {
            if (!File.Exists(path))
            {
                SendJson(res, 404, ApiResult.Fail("文件不存在: " + path));
                return;
            }
            byte[] bytes = File.ReadAllBytes(path);
            res.StatusCode = 200;
            res.ContentType = mime + "; charset=utf-8";
            res.ContentLength64 = bytes.Length;
            res.OutputStream.Write(bytes, 0, bytes.Length);
            res.OutputStream.Close();
        }
    }
}


mtv.html

<html>

<head>
    <title>MTV点歌程序</title>
    <style>
        :root {
            --color-primary-bg: #f0f8ff;
            --color-primary-text: #0056b3;
            --color-primary-bg-hover: #d1ecff;
            --color-primary-text-hover: #0056b3;
            --color-primary-text-active: #0056b3;
            --color-primary-bg-active: #d1ecff;
            --color-primary-text-active: #0056b3;
        }
    </style>
</head>

<body>
    <header class="app-header">
        <h1 class="app-title">MTV点歌程序</h1>
        <label for="search-input">搜索歌曲:<input type="text" id="search-input"></label>
        <button id="search-button" class="search-button">搜索</button>
    </header>
    <main class="app-main">
        <aside class="app-aside">
            <button class="aside-button">全部歌曲</button>
            <button class="aside-button">选中的歌曲</button>
            <button class="aside-button">设置项</button>
        </aside>
        <article class="app-article">
            <div class="app-article__musiclist" id="musiclist">

            </div>
        </article>
    </main>
    <footer class="app-footer">
        <p>...</p>
    </footer>

    <script>
        const $ = id => document.getElementById(id);

        // 页面由 C# 服务器托管时,直接用相对路径即可(同源,无跨域问题)
        async function loadSongs() {
            const r = await fetch("/api/songs");
            const json = await r.json();            // { ok, message, data }
            if (!json.ok) { alert(json.message); return; }
            $("musiclist").innerHTML = json.data
                .map(s => `<div class="song-item" data-id="${s.id}">${s.name} - ${s.singer}</div>`)
                .join("");
        }

        // 网页 → C# 发命令(POST)
        async function sendCommand(cmd) {
            await fetch("/api/command", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(cmd)
            });
        }

        loadSongs();
    </script>
</body>

</html>



先运行C#,控制输出如下:

[20:19:34] GET /mtv.html
[20:19:34] GET /api/songs
[20:19:34] GET /.well-known/appspecific/com.chrome.devtools.json      
[20:21:25] POST /api/command

然后浏览器访问 http://localhost:8088/mtv.html

看到C#端推过来的两条“假歌曲数据”,就表示GET(网页取数据)成功。

image.png

然后在网页那边按f12进入开发者模式,在控制台下测试POST(网页发命令给 C#)。

输入:

sendCommand({ cmd: "play", id: 1 })

image.png

这时候观察C#这边的输出:

[20:19:34] GET /mtv.html
[20:19:34] GET /api/songs
[20:19:34] GET /.well-known/appspecific/com.chrome.devtools.json      
[20:21:25] POST /api/command
收到网页命令: {"cmd":"play","id":1}


C#端到html端的流水线如下:

C# SongService(数据源,两条假数据)
   → JsonSerializer 序列化成 JSON(camelCase)
   → HttpListener 通过 /api/songs 发给浏览器
   → JS fetch() 收到响应 → r.json() 解析
   → map() 拼出 HTML 字符串
   → innerHTML 渲染进 #musiclist

image.png



调试三板斧 ,

后面加功能时靠它们排错:

- C# 控制台 → 看请求有没有进来、body 是什么
- F12 Console → 看 JS 有没有报错
- F12 Network → 看响应 JSON 长什么样



到现在为止,已经讲解了4种C#和html通讯的技术,下面做个总结:

image.png

就技术路线选择来说,没有绝对的“最佳”,取决于你的分发形态 。



发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

«    2026年12月    »
一 二 三 四 五 六 日
123456
78910111213
14151617181920
21222324252627
28293031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
文章归档
网站收藏
友情链接

Powered By Z-BlogPHP 1.7.3

Copyright www.skcircle.com Rights Reserved.

鄂ICP备18008319号


站长QQ:496103864 微信:abc496103864