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
相关推荐
01漫游者3 分钟前
JavaScript函数与对象增强知识
开发语言·javascript·ecmascript
IGAn CTOU4 分钟前
Java高级开发进阶教程之系列
java·开发语言
csbysj202011 分钟前
SQL NULL 函数详解
开发语言
其实防守也摸鱼14 分钟前
CTF密码学综合教学指南--第三章
开发语言·网络·python·安全·网络安全·密码学
NGSI vimp14 分钟前
Java进阶——如何查看Java字节码
java·开发语言
We་ct1 小时前
深度剖析浏览器跨域问题
开发语言·前端·浏览器·跨域·cors·同源·浏览器跨域
He少年1 小时前
【AI 辅助案例分享】
人工智能·c#·编辑器·ai编程
skywalk81631 小时前
在考虑双轨制,即在中文语法的基础上,加上数学公式的支持,这样像很多计算将更加简单方便,就像现在的小学数学课本里面一样,比如:定x=2*x + 1
开发语言
小书房1 小时前
Kotlin的by
android·开发语言·kotlin·委托·by
就叫飞六吧2 小时前
QT写一个桌面程序exe并动态打包基本流程(c++)
开发语言·c++