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
相关推荐
浪成电火花15 分钟前
(deepseek!)deepspeed中C++关联部分
开发语言·c++
茉莉玫瑰花茶18 分钟前
Qt 常用控件 - 9
开发语言·qt
艾伦~耶格尔1 小时前
【数据结构进阶】
java·开发语言·数据结构·学习·面试
杜子不疼.1 小时前
《Python列表和元组:从入门到花式操作指南》
开发语言·python
WYH2872 小时前
C#控制台输入(Read()、ReadKey()和ReadLine())
开发语言·c#
祈祷苍天赐我java之术2 小时前
Java 迭代器(Iterator)详解
java·开发语言
秋氘渔2 小时前
综合案例:Python 函数知识整合 — 学生成绩管理系统
开发语言·python
我命由我123452 小时前
软件开发 - 避免过多的 if-else 语句(使用策略模式、使用映射表、使用枚举、使用函数式编程)
java·开发语言·javascript·设计模式·java-ee·策略模式·js
long3162 小时前
java 策略模式 demo
java·开发语言·后端·spring·设计模式
hqwest3 小时前
C#WPF实战出真汁06--【系统设置】--餐桌类型设置
c#·.net·wpf·布局·分页·命令·viewmodel