HttpListener 流利简单的API

static void Main()
{
using (var server = new SimpleWebServer("http://localhost:12345/", @"D:/webroot"))
{ Console.WriteLine("http服务开始监听......"); server.Start(); while (true)
{
var inStr = Console.ReadLine(); Debug.Assert(inStr != null, "inStr != null");
if (inStr.Equals("STOP", StringComparison.OrdinalIgnoreCase))
{
break;
}
Console.WriteLine("输入 stop 可停止服务!");
}
}
} public class SimpleWebServer : IDisposable
{ private readonly HttpListener _httpListener; private readonly string _baseFolder; public SimpleWebServer(string uriPrefix, string baseFloder)
{
_httpListener = new HttpListener();
_httpListener.Prefixes.Add(uriPrefix);
_baseFolder = baseFloder;
} public async void Start()
{
_httpListener.Start(); while (true)
{
try
{
var context = await _httpListener.GetContextAsync();
#pragma warning disable 4014
Task.Factory.StartNew(() =>{
PrcessRequestAsync(context);
}); }
catch (HttpListenerException exception)
{
Console.WriteLine(exception);
break;
}
catch (InvalidOperationException exception)
{
Console.WriteLine(exception); break;
}
}
} private async void PrcessRequestAsync(HttpListenerContext context)
{
try
{
string filename = Path.GetFileName(context.Request.RawUrl); // ReSharper disable once AssignNullToNotNullAttribute
string path = Path.Combine(_baseFolder, filename); byte[] msg = new byte[0];
if (File.Exists(path))
{
if (context.Request.HttpMethod == "GET")
{
context.Response.StatusCode = (int) HttpStatusCode.OK;
msg = File.ReadAllBytes(path);
}
else if (context.Request.HttpMethod=="POST")
{
context.Response.StatusCode = (int)HttpStatusCode.Created; }
else
{
context.Response.StatusCode = (int) HttpStatusCode.HttpVersionNotSupported;
} }
else
{
Console.WriteLine($"资源不存在:{path}"); context.Response.StatusCode = (int) HttpStatusCode.NotFound; msg = Encoding.Default.GetBytes(" ...你网址打错了... ");
} context.Response.ContentLength64 = msg.Length; using (Stream s = context.Response.OutputStream)
{
await s.WriteAsync(msg, 0, msg.Length); }
}
catch (Exception exception)
{
Console.WriteLine($"请求发生了错误:{exception}");
}
} public void Dispose()
{
_httpListener.Stop();
}
}

效果:

教学小例子:简易的webSevrer-LMLPHP

教学小例子:简易的webSevrer-LMLPHP

教学小例子:简易的webSevrer-LMLPHP

教学小例子:简易的webSevrer-LMLPHP

教学小例子:简易的webSevrer-LMLPHP

05-11 15:57