8,834
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LocalHtml
{
public partial class Form1 : Form
{
private const string Host = "http://127.0.0.1:4723/";
private readonly HttpListener _httpListener;
public Form1()
{
InitializeComponent();
_httpListener = new HttpListener();
_httpListener.Prefixes.Add(Host);
_httpListener.Start();
var wwwroot = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot");
var response404 = File.ReadAllBytes(Path.Combine(wwwroot, "404.html"));
var response500 = File.ReadAllBytes(Path.Combine(wwwroot, "500.html"));
var allPath = Directory.GetFiles(wwwroot).ToDictionary(m => m.Replace(wwwroot, string.Empty).Replace('\\', '/').ToUpperInvariant(), m => m);
Task.Run(async () =>
{
while (true)
{
var httpContext = await _httpListener.GetContextAsync().ConfigureAwait(false);
var request = httpContext.Request;
var responseData = Array.Empty<byte>();
var statusCode = (int)HttpStatusCode.OK;
try
{
var path = request.Url.LocalPath?.ToUpperInvariant();
if (path != null && allPath.ContainsKey(path))
{
responseData = File.ReadAllBytes(allPath[path]);
}
else
{
statusCode = (int)HttpStatusCode.NotFound;
responseData = response404;
}
}
catch
{
statusCode = (int)HttpStatusCode.InternalServerError;
responseData = response500;
}
finally
{
try
{
httpContext.Response.ContentType = "text/html";
httpContext.Response.StatusCode = statusCode;
httpContext.Response.Close(responseData, true);
}
catch (Exception) { }
}
}
});
webBrowser1.Navigate(Path.Combine(Host, "index.html"));
}
}
}