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
相关推荐
会讲英语的码农几秒前
php基础
开发语言·后端·php
ptu小鹏4 小时前
类和对象(中)
开发语言·c++
Bayi·6 小时前
前端面试场景题
开发语言·前端·javascript
碎梦归途6 小时前
23种设计模式-结构型模式之享元模式(Java版本)
java·开发语言·jvm·设计模式·享元模式
Xiaoyu Wang6 小时前
Go协程的调用与原理
开发语言·后端·golang
bigear_码农7 小时前
python异步协程async调用过程图解
开发语言·python·线程·进程·协程
知识分享小能手7 小时前
JavaScript学习教程,从入门到精通,Ajax与Node.js Web服务器开发全面指南(24)
开发语言·前端·javascript·学习·ajax·node.js·html5
凌叁儿7 小时前
Python 的 datetime 模块使用详解
开发语言·python
谁家有个大人7 小时前
Python数据清洗笔记(上)
开发语言·笔记·python·数据分析
EanoJiang8 小时前
CSharp_base
c#