using Microsoft.Owin; using Microsoft.Owin.Hosting; using Nancy.Hosting.Self; using Owin; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http.Formatting; using System.Text; using System.Threading.Tasks; using System.Web.Http; using static System.Net.Mime.MediaTypeNames; namespace 电子展板 { public class WebServer { private static bool UseNancy = false; private static NancyHost _host; private static IDisposable host; public static void Start() { if (UseNancy) { _host = new NancyHost(new Uri("http://localhost:80")); _host.Start(); } else { StartOptions startOptions = new StartOptions(); startOptions.Urls.Add($"http://*:80/"); host = WebApp.Start(startOptions); } } public static void Stop() { if (_host != null) { _host.Stop(); _host.Dispose(); _host = null; } if (host != null) { host.Dispose(); host = null; } } } /// /// Web启动类 /// public class Startup { private HttpConfiguration _config; /// /// 配置 /// /// /// public void Configuration(IAppBuilder app) { _config = new HttpConfiguration(); _config.MapHttpAttributeRoutes(); _config.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); _config.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("datatype", "json", "application/json")); //全局拦截 app.Use("/static", "/Assets"); app.UseWebApi(_config); } } public class ResouceStaticRoute : OwinMiddleware { private string route; private string resources; public ResouceStaticRoute(OwinMiddleware next, string route, string resources) : base(next) { this.route = route; this.resources = resources; } public override async Task Invoke(IOwinContext context) { try { string method = context.Request.Method;//GET POST string path = context.Request.Path.ToString(); if (method.ToUpper() == "GET" && path.StartsWith(route)) { string resourePath = path.Replace(route, ""); string packUri = $"pack://application:,,,{resources}{resourePath}"; byte[] bytes = null; using (Stream stream = System.Windows.Application.GetResourceStream(new Uri(packUri, UriKind.RelativeOrAbsolute)).Stream) { bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); } context.Response.ContentType = System.Web.MimeMapping.GetMimeMapping(path); context.Response.Write(bytes, 0, bytes.Length); await Task.FromResult(0); } await Next.Invoke(context); } catch (InvalidCastException ex) { await Next.Invoke(context); } catch (Exception ex) { await Next.Invoke(context); } } } }