C#如何实现一个简单的Web服务器 HttpListener使用教程

来源:这里教程网 时间:2026-02-21 17:39:44 作者:

HttpListener
实现一个轻量级 Web 服务器,在 C# 中非常直接,适合做本地调试、微服务接口或嵌入式 HTTP 响应场景。它不依赖 IIS 或 Kestrel,开箱即用,但仅支持 Windows(.NET Framework 和 .NET Core/.NET 5+ 在 Windows 上可用)。

基础准备:启用权限与引用命名空间

Windows 上运行

HttpListener
需要 HTTP 命名空间保留权限(尤其非管理员账户),否则会抛出
AccessDeniedException
。可提前执行命令(管理员权限运行):

netsh http add urlacl url=http://+:8080/ user=DOMAIN\username

代码中需引入命名空间:

using System;
using System.IO;
using System.Net;
using System.Text;

最简可用的监听循环

核心逻辑是:启动监听 → 等待请求 → 读取并响应 → 关闭连接。注意必须调用

context.Response.Close()
或使用
using
显式释放流,否则连接挂起。

创建实例并指定前缀(如
http://localhost:8080/
调用
Start()
开始监听
GetContext()
同步等待请求(阻塞,适合简单场景)
写响应时设置
ContentType
ContentLength64
(推荐)

var listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();

Console.WriteLine("Server running at http://localhost:8080/");
while (true)
{
  var context = listener.GetContext();
  var response = context.Response;
  string html = "

Hello from HttpListener

";
  byte[] buffer = Encoding.UTF8.GetBytes(html);
  response.ContentType = "text/html";
  response.ContentLength64 = buffer.Length;
  response.OutputStream.Write(buffer, 0, buffer.Length);
  response.Close(); // 必须关闭
}

支持 GET 参数与路径路由

context.Request.Url
提供完整 URI,可用
PathAndQuery
区分路径和参数,
QueryString
属性自动解析键值对。

例如访问
http://localhost:8080/api/user?id=123
context.Request.QueryString["id"]
返回
"123"
switch(context.Request.Url.LocalPath)
做简易路由
注意 URL 解码:查询字符串值默认已解码,路径部分需手动调用
Uri.UnescapeDataString()

异步处理与多请求支持

GetContext()
是同步阻塞的,一次只能处理一个请求。生产环境建议改用
BeginGetContext / EndGetContext
或更现代的
GetContextAsync()
(.NET Core 2.1+ 支持)。

GetContextAsync()
返回
Task<httplistenercontext></httplistenercontext>
,配合
await
不阻塞主线程
每个请求应在独立任务中处理,避免串行延迟 记得捕获异常(如客户端断连导致的
IOException
),防止整个监听崩溃

async Task HandleRequest(HttpListenerContext ctx)
{
  try
  {
    // 处理逻辑...
  }
  catch (IOException) { /* 客户端意外断开 */ }
  finally { ctx.Response.Close(); }
}

基本上就这些。HttpListener 轻巧可控,适合学习 HTTP 底层交互或构建极简后端;若需路由、中间件、HTTPS、跨平台等能力,建议升级到 ASP.NET Core 的

WebHost
Minimal API

相关推荐