using Microsoft.AspNetCore.Cors; using Microsoft.Owin; using Microsoft.Owin.Cors; using Microsoft.Owin.FileSystems; using Microsoft.Owin.Hosting; using Microsoft.Owin.StaticFiles; using Newtonsoft.Json; using Owin; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Net; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Http; using System.Web.Mvc; namespace Server { internal class OwinServer { public static string RootDir = CsharpHttpHelper.HttpExtend.MapPath("网站");// Directory.GetCurrentDirectory() + "\\网站"; /// /// 查找本地数据,无数据 返回index /// /// /// public static string GetFilePath(string relPath) { if (string.IsNullOrEmpty(relPath) || relPath == "/") { relPath = "index.html"; } return Path.Combine( AppDomain.CurrentDomain.BaseDirectory , RootDir , relPath.TrimStart('/').Replace('/', '\\')); } /// /// 设置返回contenttype 并返回数据 /// /// /// /// public Task SetResponse(IOwinContext context, string path) { var perfix = Path.GetExtension(path); switch (perfix) { case ".html": context.Response.ContentType = "text/html; charset=utf-8"; break; case ".js": context.Response.ContentType = "application/x-javascript"; break; case ".css": context.Response.ContentType = "text/css"; break; case ".jpg": case ".jpeg": context.Response.ContentType = "image/jpeg"; break; case ".png": context.Response.ContentType = "application/x-png"; break; case ".mp4": context.Response.ContentType = "video/mpeg4"; break; case ".webp": context.Response.ContentType = "image/webp"; break; case ".gif": context.Response.ContentType = "image/gif"; break; case ".woff2": context.Response.ContentType = "application/x-font-woff"; break; case ".ico": context.Response.ContentType = "image/x-icon"; break; } return context.Response.WriteAsync(File.ReadAllText(path)); } /// /// 执行API /// /// /// /// private Task TodoApi(IOwinContext context, Func next) { //var response = new WebResult(); //try //{ // var query = context.Request.Query.ToString(); // //Dictionary Param = new Dictionary(); // //var contentType = context.Request.ContentType; // //if (context.Request.Method.ToLower() == "post") // //{ // // if (contentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) // // { // // string body = new StreamReader(context.Request.Body, Encoding.UTF8).ReadToEnd(); // // var postdata =new NameValueCollection(StringComparer.OrdinalIgnoreCase); // // ///Util.GetQueryString(body, Encoding.UTF8); // // if (postdata != null) // // { // // foreach (var item in postdata.AllKeys) // // { // // Param[item] = HttpUtility.UrlEncode(postdata[item]); // // } // // } // // } // //} // //if (context.Request.Query != null && context.Request.Query.Count() > 0) // //{ // // foreach (var item in context.Request.Query) // // { // // if (item.Value != null && item.Value.Length > 0) Param[item.Key] = HttpUtility.UrlDecode(item.Value[0]); // // } // //} // //if (EventClient.StopParsing) return next(); // //var plugins = PluginClient.Plugins.ToArray(); // //var events = new WebRequestEvents(context, Param, response); // ////正常事件解析 // //foreach (var plugin in plugins) // //{ // // if (!plugin.IsRun) continue;//未运行 // // if (events.Cancel) break;//已取消传递 // // plugin.SDK.OnEvent(context, events); // //} //} //catch (Exception ex) //{ // response.code = -1; // response.errMsg = ex.Message; //} //if (string.IsNullOrEmpty(response.)) //{ // response.ok = false; // response.errMsg = $"请求成功,但未响应结果!{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}"; //} //var msg = JsonConvert.SerializeObject(response); context.Response.StatusCode = (int)HttpStatusCode.OK; return context.Response.WriteAsync("无响应结果"); } /// /// 挂载数据 分流静态文件及接口请求 /// /// /// /// public async Task RequestHandler(IOwinContext context, Func next) { try { var path = GetFilePath(context.Request.Path.Value); if (File.Exists(path)) { await SetResponse(context, path); } else { await TodoApi(context, next); } } catch (Exception) { } await next(); } public void Configuration(Owin.IAppBuilder appBuilder) { appBuilder.UseCors(CorsOptions.AllowAll); var config = new HttpConfiguration(); config.MapHttpAttributeRoutes(); // config.Routes.MapHttpRoute( // name: "DefaultApi", // routeTemplate: "api/{controller}/{id}" //); config.Routes.MapHttpRoute( name: "Default", routeTemplate: "{controller}/{action}/{id}", defaults: new { controller = "abbb", action = "Index", id = UrlParameter.Optional } ); ///@".\wwwroot" var physicalFileSystem = new PhysicalFileSystem(RootDir); var options = new FileServerOptions { EnableDefaultFiles = true, FileSystem = physicalFileSystem }; options.StaticFileOptions.FileSystem = physicalFileSystem; options.StaticFileOptions.ServeUnknownFileTypes = true; options.DefaultFilesOptions.DefaultFileNames = new[] { "Index.html" }; appBuilder.UseFileServer(options); appBuilder.UseWebApi(config); /* app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapRazorPages(); app.Run(); */ } } }