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
相关推荐
艾莉丝努力练剑21 分钟前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
倔强青铜34 小时前
苦练Python第18天:Python异常处理锦囊
开发语言·python
u_topian5 小时前
【个人笔记】Qt使用的一些易错问题
开发语言·笔记·qt
珊瑚里的鱼5 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
AI+程序员在路上5 小时前
QTextCodec的功能及其在Qt5及Qt6中的演变
开发语言·c++·qt
xingshanchang5 小时前
Matlab的命令行窗口内容的记录-利用diary记录日志/保存命令窗口输出
开发语言·matlab
Risehuxyc6 小时前
C++卸载了会影响电脑正常使用吗?解析C++运行库的作用与卸载后果
开发语言·c++
时光追逐者6 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 46 期(2025年7.7-7.13)
c#·.net·.netcore
AI视觉网奇6 小时前
git 访问 github
运维·开发语言·docker
不知道叫什么呀6 小时前
【C】vector和array的区别
java·c语言·开发语言·aigc