C#高级:用控制台程序模拟WebAPI处理接口请求信息

1.基础Demo

cs 复制代码
class Program
{
    static void Main()
    {
        // 创建 HttpListener 实例
        HttpListener listener = new HttpListener();

        // 添加监听的前缀(模拟 Web API 路径)
        listener.Prefixes.Add("http://localhost:18110/api/");

        // 启动监听
        listener.Start();
        Console.WriteLine("API Server is running...");

        // 在一个单独的线程中处理请求
        ThreadPool.QueueUserWorkItem(HandleRequests, listener);

        // 持续运行,直到按下任意键停止
        Console.ReadLine();
        listener.Stop();
    }

    // 处理请求的函数
    static void HandleRequests(object obj)
    {
        HttpListener listener = (HttpListener)obj;

        while (listener.IsListening)
        {
            // 获取客户端请求
            HttpListenerContext context = listener.GetContext();
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;

            // 根据请求的 URL 路径做不同的处理
            string responseText = string.Empty;
            if (request.Url.AbsolutePath == "/api/hello")
            {
                responseText = "{\"message\":\"Hello, World!\"}";
            }
            else if (request.Url.AbsolutePath == "/api/greet")
            {
                // 从查询字符串获取名字参数
                string name = request.QueryString["name"] ?? "Guest";
                responseText = $"{{\"message\":\"Hello, {name}!\"}}";
            }
            else
            {
                responseText = "{\"error\":\"Invalid API endpoint\"}";
            }

            // 设置响应的内容类型和编码
            byte[] buffer = Encoding.UTF8.GetBytes(responseText);
            response.ContentType = "application/json";
            response.ContentLength64 = buffer.Length;

            // 发送响应
            response.OutputStream.Write(buffer, 0, buffer.Length);
            response.OutputStream.Close();
        }
    }
}

2.使用Postman测试

bash 复制代码
http://localhost:18110/api/hello
http://localhost:18110/api/greet?name=susu

3.注意事项

端口不能被重复占用,如果有,请换一个端口

bash 复制代码
Failed to listen on prefix 'http://localhost:18110/api/' because it conflicts with an existing registration on the machine
相关推荐
MediaTea4 分钟前
Python 第三方库:PyTorch(动态计算图的深度学习框架)
开发语言·人工智能·pytorch·python·深度学习
Boop_wu25 分钟前
[Java EE] 多线程 -- 初阶(3)
java·开发语言
2301_7951672027 分钟前
玩转Rust高级应用 如何理解 Rust 实现免疫数据竞争的关键是Send 和 Sync 这两个 trait
开发语言·算法·rust
云和数据.ChenGuang39 分钟前
Python 3.14 与 PyCharm 2025.2.1 的调试器(PyDev)存在兼容性问题
开发语言·python·pycharm
Mr.Jessy1 小时前
Web APIs 学习第六天:BOM、location对象与本地存储
开发语言·前端·javascript·学习·web api·bom
LIZhang20162 小时前
基于ffmpeg8.0录制mp4文件
开发语言·c++
一个帅气昵称啊2 小时前
在.NET中使用RAG检索增强AI基于Qdrant的矢量化数据库
ai·性能优化·c#·.net·rag·qdrant
_OP_CHEN2 小时前
C++进阶:(九)深度剖析unordered_map 与 unordered_set容器
开发语言·c++·stl容器·哈希表·哈希桶·unordered_map·unordered_set
七夜zippoe2 小时前
Java并发编程基石:深入理解JMM(Java内存模型)与Happens-Before规则
java·开发语言·spring·jmm·happens-before
Mark Studio2 小时前
QT linux 静态编译问题记录
开发语言·qt