using System.IO; using System.Net; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Laservall.Solidworks.Server { internal static class StaticFileHandler { private const string ResourceName = "Laservall.Solidworks.Resources.index.html"; public static async Task ServeIndex(HttpListenerContext context, string authToken, CancellationToken ct) { byte[] html = GetIndexHtml(authToken); if (html == null) { context.Response.StatusCode = 500; byte[] err = Encoding.UTF8.GetBytes("SPA resource not found"); context.Response.ContentLength64 = err.Length; await context.Response.OutputStream.WriteAsync(err, 0, err.Length, ct); context.Response.Close(); return; } context.Response.StatusCode = 200; context.Response.ContentType = "text/html; charset=utf-8"; context.Response.ContentLength64 = html.Length; context.Response.Headers.Set("Cache-Control", "no-cache, no-store, must-revalidate"); await context.Response.OutputStream.WriteAsync(html, 0, html.Length, ct); context.Response.Close(); } private static byte[] GetIndexHtml(string authToken) { var assembly = Assembly.GetExecutingAssembly(); using (var stream = assembly.GetManifestResourceStream(ResourceName)) { if (stream == null) { return GetPlaceholderHtml(); } using (var reader = new StreamReader(stream, Encoding.UTF8)) { string html = reader.ReadToEnd(); html = html.Replace("{AUTH_TOKEN}", authToken); return Encoding.UTF8.GetBytes(html); } } } private static byte[] GetPlaceholderHtml() { string html = @"
SPA 尚未构建。请运行 npm run build 并嵌入到程序集资源中。