C#构建HTTP服务器实现GET方法
时间: 2024-09-13 16:14:28 浏览: 47
在C#中,你可以使用内置的`System.Net.HttpListener`类来创建一个简单的HTTP服务器,尤其是用于处理GET请求。这里是一个基本的例子:
```csharp
using System;
using System.Net;
using System.IO;
class SimpleHttpServer
{
private HttpListener listener = new HttpListener();
public void Start()
{
// 设置监听端口
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
Console.WriteLine("Server started on port 8080. Press any key to stop.");
// 监听并处理请求
Console.ReadKey();
listener.Stop();
listener.Close();
}
private void HandleRequest(HttpListenerContext context)
{
if (context.Request.HttpMethod == "GET")
{
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "index.html"); // 文件路径假设是当前目录下的index.html
try
{
// 读取文件内容
byte[] fileBytes = File.ReadAllBytes(filePath);
context.Response.ContentType = "text/html";
context.Response.ContentLength64 = fileBytes.Length;
using (var responseStream = context.Response.OutputStream)
{
responseStream.Write(fileBytes, 0, fileBytes.Length);
}
}
catch (Exception ex)
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.StatusDescription = ex.Message;
}
}
else
{
context.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
context.Response.StatusDescription = "Only GET method is supported.";
}
}
// 等待新的连接
private void ListenForRequests()
{
while (true)
{
HttpListenerContext context = listener.GetContext();
HandleRequest(context);
}
}
}
public static class Program
{
public static void Main(string[] args)
{
var server = new SimpleHttpServer();
server.Start();
server.ListenForRequests();
}
}
```
当你运行这个程序后,它会在本地8080端口上监听GET请求,并返回指定目录下的index.html文件。如果请求方法不是GET,它会返回一个错误响应。
阅读全文