.NET Framework 自托管详解
.NET Framework 自托管详解 自托管(Self-Hosting)是指不依赖 IIS 等外部 Web 服务器,而是通过应用程序自身创建和管理 Web 服务器实例的方式运行 Web 应用程序。 1. HttpListener 方式 这是最基础的自托管方式,使用 .NET Framework 内置的 HttpListener 类: using System; using System.IO; using System.Net; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { // 创建 HttpListener 实例 HttpListener listener = new HttpListener(); // 添加监听的 URL 前缀 listener.Prefixes.Add("http://localhost:8080/"); // 启动监听 listener.Start(); Console.WriteLine("服务器启动,监听 http://localhost:8080/"); // 处理请求循环 while (true) { // 等待请求 HttpListenerContext context = await listener.GetContextAsync(); // 处理请求 await ProcessRequest(context); } } static async Task ProcessRequest(HttpListenerContext context) { HttpListenerResponse response = context.Response; // 设置响应内容 string responseString = "<html><body><h1>Hello from Self-Hosted Server!</h1></body></html>"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); // 设置响应头 response.ContentType = "text/html"; response.ContentLength64 = buffer.Length; // 写入响应 using (Stream output = response.OutputStream) { await output.WriteAsync(buffer, 0, buffer.Length); } // 关闭响应 response.Close(); } } 2. ASP.NET Web API 自托管 使用 Microsoft.AspNet.WebApi.SelfHost 包可以创建更完整的 Web API 服务: ...