在C#中搭建简易HTTP服务器最方便的方式是使用System.Net命名空间下的HttpListener类。它不需要依赖IIS,直接以控制台或窗体程序运行就能监听本地端口并处理HTTP请求。

一、HttpListener基本使用步骤
使用HttpListener一般包含以下几个环节:创建实例、添加监听前缀、启动监听、循环接收请求、处理并响应、关闭释放。其中监听前缀需要以斜杠结尾,例如 http://127.0.0.1:8080/。
1. 创建并配置HttpListener
通过new HttpListener()实例化后,调用Prefixes.Add方法设置要监听的地址,再调用Start方法启动。
2. 接收与处理请求
调用GetContext方法会阻塞线程直到有请求进来,返回HttpListenerContext对象,从中可以拿到请求信息和响应对象。
二、完整源码示例
下面给出一个最简单的C#控制台程序,监听127.0.0.1的8080端口,访问后返回一段文本。
using System;
using System.Net;
using System.Text;
class SimpleHttpServer
{
static void Main()
{
// 创建HttpListener实例
HttpListener listener = new HttpListener();
// 添加监听前缀,必须以/结尾
listener.Prefixes.Add("http://127.0.0.1:8080/");
// 启动监听
listener.Start();
Console.WriteLine("服务器已启动,访问 http://127.0.0.1:8080/");
// 循环处理请求
while (true)
{
// 等待并获取请求上下文
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
// 构造返回内容
string responseString = "<html><body>Hello from C# HttpListener!</body></html>";
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
// 设置响应头和内容
response.ContentType = "text/html; charset=utf-8";
response.ContentLength64 = buffer.Length;
response.OutputStream.Write(buffer, 0, buffer.Length);
response.OutputStream.Close();
}
}
}
三、常见问题与注意点
- 如果启动时报“拒绝访问”,需要用管理员权限运行,或改用大于1024的端口。
- Prefixes里的地址不能重复被其他程序占用,否则Start会抛异常。
- 示例中使用while(true)会一直阻塞主线程,实际项目可放到单独线程或配合async方法。
四、返回JSON数据示例
如果要把接口返回改成JSON,只需要调整Content-Type和返回字符串:
string json = "{"code":0,"msg":"ok"}";
byte[] data = Encoding.UTF8.GetBytes(json);
response.ContentType = "application/json; charset=utf-8";
response.ContentLength64 = data.Length;
response.OutputStream.Write(data, 0, data.Length);
response.OutputStream.Close();
通过上述方式,你可以用C#和HttpListener在几分钟内搭好一个本地HTTP服务,满足调试和轻量接口需求。
C#HttpListenerHTTP服务器修改时间:2026-07-28 22:21:18