简化WEB库

This commit is contained in:
2025-09-23 10:38:35 +08:00
parent 9a89a138dd
commit c6037c51ed
17 changed files with 165 additions and 780 deletions

View File

@@ -1,4 +1,5 @@
using System; using Nancy.Hosting.Self;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
@@ -11,6 +12,8 @@ namespace 电子展板.Base
{ {
public class GlobalVariable public class GlobalVariable
{ {
public static NancyHost WebServer;
private static MyConfig _config; private static MyConfig _config;
/// <summary> /// <summary>
/// 配置数据 /// 配置数据

View File

@@ -1,207 +0,0 @@
using JinianNet.JNTemplate;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;
using System.Xml.Linq;
using .Utility.Core;
using .Utility.Extension;
using .Utility.ResponseModels;
namespace .Controller
{
public class BaseController : ApiController
{
protected ActionResult Content(string content)
{
return new ActionResult { Content = new StringContent(content, Encoding.UTF8, "text/plain") };
}
protected ActionResult ContentType(string content, string contentType)
{
return new ActionResult { Content = new StringContent(content, Encoding.UTF8, contentType) };
}
public new ActionResult Redirect(string url)
{
ActionResult resp = new ActionResult(HttpStatusCode.Moved);
string originalString = Request.RequestUri.OriginalString;
string pathAndQuery = Request.RequestUri.PathAndQuery;
string baseUrl = originalString.Substring(0, originalString.IndexOf(pathAndQuery));
resp.Headers.Location = new Uri(baseUrl + url);
return resp;
}
protected ActionResult File(string virtualPath, string contentType)
{
return File(virtualPath, contentType, "HelloWorld");
}
protected ActionResult File(string virtualPath, string contentType, string fileDownloadName)
{
string physicalPath = MyEnvironment.WebRootPath(virtualPath);
return PhysicalFile(physicalPath, contentType, fileDownloadName);
}
protected ActionResult PhysicalFile(string physicalPath, string contentType)
{
return PhysicalFile(physicalPath, contentType, "HelloWorld");
}
protected ActionResult PhysicalFile(string physicalPath, string contentType, string fileDownloadName)
{
return File(System.IO.File.OpenRead(physicalPath), contentType, fileDownloadName);
}
protected ActionResult File(byte[] fileContents, string contentType)
{
return File(fileContents, contentType, "HelloWorld");
}
protected ActionResult File(byte[] fileContents, string contentType, string fileDownloadName)
{
ActionResult response = new ActionResult(HttpStatusCode.OK);
response.Content = new ByteArrayContent(fileContents);
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
response.Content.Headers.ContentLength = fileContents.Length;
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = HttpUtility.UrlEncode(fileDownloadName)
};
response.Headers.Add("Access-Control-Expose-Headers", "FileName");
response.Headers.Add("FileName", HttpUtility.UrlEncode(fileDownloadName));
return response;
}
protected ActionResult File(Stream fileStream, string contentType)
{
return File(fileStream, contentType, "HelloWorld");
}
protected ActionResult File(Stream fileStream, string contentType, string fileDownloadName)
{
ActionResult response = new ActionResult(HttpStatusCode.OK);
response.Content = new StreamContent(fileStream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
response.Content.Headers.ContentLength = fileStream.Length;
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = HttpUtility.UrlEncode(fileDownloadName)
};
response.Headers.Add("Access-Control-Expose-Headers", "FileName");
response.Headers.Add("FileName", HttpUtility.UrlEncode(fileDownloadName));
return response;
}
#region
protected ActionResult Success(string message = "恭喜您,操作成功。", object data = null)
{
return Content(new AjaxResult(ResultType.Success, message, data).ToJson());
}
protected ActionResult Error(string message = "对不起,操作失败。", object data = null)
{
return Content(new AjaxResult(ResultType.Error, message, data).ToJson());
}
protected ActionResult Warning(string message, object data = null)
{
return Content(new AjaxResult(ResultType.Warning, message, data).ToJson());
}
protected ActionResult Info(string message, object data = null)
{
return Content(new AjaxResult(ResultType.Info, message, data).ToJson());
}
public ActionResult Json(object obj)
{
return new ActionResult { Content = new StringContent(obj.ToJson(), Encoding.UTF8, "application/json") };
}
public ActionResult Text(string str)
{
//return Content(str, "text/plain");
return new ActionResult { Content = new System.Net.Http.StringContent(str, Encoding.UTF8, "text/plain") };
}
public ActionResult HtmlStr(string str)
{
return new ActionResult { Content = new System.Net.Http.StringContent(str, Encoding.UTF8, "text/html") };
}
public ActionResult Html(string view)
{
return Html(view, null);
}
public ActionResult Resouce(string viewName, string contentType)
{
string packUri = $"pack://application:,,,/Assets{viewName}";
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);
}
ActionResult response = new ActionResult(HttpStatusCode.OK);
response.Content = new ByteArrayContent(bytes);
response.Content.Headers.ContentEncoding.Add("utf-8");
response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
response.Content.Headers.ContentLength = bytes.Length;
return response;
}
public ActionResult Html(string view, Dictionary<string, object> dict)
{
if (!view.StartsWith("/"))
view = "/" + view;
string path = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "/") + "Views";
var template = Engine.LoadTemplate(path + view + ".html");
if (dict != null)
{
foreach (KeyValuePair<string, object> keyValue in dict)
{
template.Set(keyValue.Key, keyValue.Value);
}
}
var result = template.Render();
// return Content(result, "text/html");
return new ActionResult { Content = new System.Net.Http.StringContent(result, Encoding.UTF8, "text/html") };
}
#endregion
}
}
namespace Microsoft.AspNetCore.Mvc
{
public class ActionResult : System.Net.Http.HttpResponseMessage
{
public ActionResult() : base(HttpStatusCode.OK)
{
}
public ActionResult(HttpStatusCode statusCode) : base(statusCode)
{
}
}
}

View File

@@ -1,105 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Web.Http;
using .Base;
using .Utility;
using .Utility.Core;
using .Utility.Extension;
using .Utility.Logs;
using .Utility.Other;
using .Utility.Web;
namespace .Controller
{
public class IndexController : BaseController
{
/// <summary>
/// 主界面
/// </summary>
/// <returns></returns>
[HttpGet, Route(""), Route("index.html")]
public ActionResult Index()
{
return Resouce("/Views/Index.html", "text/html");
}
/// <summary>
/// 获得配置信息
/// </summary>
/// <returns></returns>
[HttpGet, Route("getConfig")]
public ActionResult GetConfig()
{
return Json(GlobalVariable.Config);
}
/// <summary>
/// 上传图片。
/// </summary>
/// <returns></returns>
[HttpPost, Route("uploadImage")]
public ActionResult UploadImage()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string path = MyEnvironment.Root("/Upload");
var provider = new WithExtensionMultipartFormDataStreamProvider(path, UUID.StrSnowId);
var fileData = Request.Content.ReadAsMultipartAsync(provider).Result;
if (fileData.FileData.Count == 0)
{
return Error();
}
var file = fileData.FileData[0];
string virtualPath = "/Upload/" + Path.GetFileName(file.LocalFileName);
return Success("上传成功", virtualPath);
}
/// <summary>
/// 图形显示
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet, Route("Upload/{id}")]
public ActionResult GetUploadFile([FromUri] string id)
{
string filePath = MyEnvironment.Root($"/Upload/{id}");
string contentType = System.Web.MimeMapping.GetMimeMapping(filePath);
return PhysicalFile(filePath, contentType, id);
}
/// <summary>
/// 保存配置文件
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
[HttpPost, Route("save")]
public ActionResult Save([FromBody] MyConfig config)
{
LogHelper.Instance.Info($"用户保存了配置:{JsonHelper.ToJson(config)}");
//保存
PropertyInfo[] propertyInfos = typeof(MyConfig).GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
object value = propertyInfo.GetValue(config);
propertyInfo.SetValue(GlobalVariable.Config, value);
}
GlobalVariable.SaveConfig();
//保存并修改界面
EventBus.Instance.Publish("save", "");
return Success();
}
}
}

View File

@@ -1,6 +1,4 @@
using Microsoft.Extensions.DependencyInjection; using System;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;

View File

@@ -1,58 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace .Utility.ResponseModels
{
/// <summary>
/// 通用AJAX请求响应数据格式模型。
/// </summary>
public class AjaxResult
{
public AjaxResult(ResultType state, string message, object data = null)
{
this.state = state;
this.message = message;
this.data = data;
}
/// <summary>
/// 结果类型。
/// </summary>
public ResultType state { get; set; }
/// <summary>
/// 消息内容。
/// </summary>
public string message { get; set; }
/// <summary>
/// 返回数据。
/// </summary>
public object data { get; set; }
}
/// <summary>
/// 结果类型枚举。
/// </summary>
public enum ResultType
{
/// <summary>
/// 警告。
/// </summary>
Warning = 0,
/// <summary>
/// 成功。
/// </summary>
Success = 1,
/// <summary>
/// 异常。
/// </summary>
Error = 2,
/// <summary>
/// 消息。
/// </summary>
Info = 6
}
}

View File

@@ -1,51 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace .Utility.ResponseModels
{
/// <summary>
/// 菜单视图模型。
/// </summary>
public class LayNavbar
{
/// <summary>
/// 标题
/// </summary>
public string title { get; set; }
/// <summary>
/// 图标
/// </summary>
public string icon { get; set; }
/// <summary>
/// 是否展开
/// </summary>
public bool spread { get; set; }
/// <summary>
/// 子级菜单集合
/// </summary>
public List<LayChildNavbar> children { get; set; }
}
/// <summary>
/// 子级菜单模型。
/// </summary>
public class LayChildNavbar
{
/// <summary>
/// 标题
/// </summary>
public string title { get; set; }
/// <summary>
/// 图标
/// </summary>
public string icon { get; set; }
/// <summary>
/// 链接
/// </summary>
public string href { get; set; }
}
}

View File

@@ -1,37 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace .Utility.ResponseModels
{
/// <summary>
/// Laytpl + Laypage 分页模型。
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public class LayPadding<TEntity> where TEntity : class
{
public int code { get; set; }
/// <summary>
/// 获取结果。
/// </summary>
public bool result { get; set; }
/// <summary>
/// 备注信息。
/// </summary>
public string msg { get; set; }
/// <summary>
/// 数据列表。
/// </summary>
public List<TEntity> list { get; set; }
public string backgroundImage { get; set; }
/// <summary>
/// 记录条数。
/// </summary>
public long count { get; set; }
}
}

View File

@@ -1,35 +0,0 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace .Utility.ResponseModels
{
public class LayPaddingDataTable
{
public int code { get; set; }
/// <summary>
/// 获取结果。
/// </summary>
public bool result { get; set; }
/// <summary>
/// 备注信息。
/// </summary>
public string msg { get; set; }
/// <summary>
/// 数据列表。
/// </summary>
public DataTable list { get; set; }
public string backgroundImage { get; set; }
/// <summary>
/// 记录条数。
/// </summary>
public long count { get; set; }
}
}

View File

@@ -1,11 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace .Utility.ResponseModels
{
public class RetStr
{
public string Data { get; set; }
}
}

View File

@@ -1,55 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json;
namespace .Utility.ResponseModels
{
/// <summary>
/// Select2树形下拉列表模型。
/// </summary>
public class TreeSelect
{
public string id { get; set; }
public string text { get; set; }
public string parentId { get; set; }
public object data { get; set; }
}
public static class TreeSelectHelper
{
public static string ToTreeSelectJson(this List<TreeSelect> data)
{
StringBuilder sb = new StringBuilder();
sb.Append("[");
sb.Append(ToTreeSelectJson(data, "0", ""));
sb.Append("]");
return sb.ToString();
}
private static string ToTreeSelectJson(List<TreeSelect> data, string parentId, string blank)
{
StringBuilder sb = new StringBuilder();
var childList = data.FindAll(t => t.parentId == parentId);
var tabline = "";
if (parentId != "0")
{
tabline = "  ";
}
if (childList.Count > 0)
{
tabline = tabline + blank;
}
foreach (TreeSelect entity in childList)
{
entity.text = tabline + entity.text;
string strJson = JsonConvert.SerializeObject(entity);
sb.Append(strJson);
sb.Append(ToTreeSelectJson(data, entity.id, tabline));
}
return sb.ToString().Replace("}{", "},{");
}
}
}

View File

@@ -1,34 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace .Utility.ResponseModels
{
/// <summary>
/// zTree单层节点数据模型。
/// </summary>
public class ZTreeNode
{
/// <summary>
/// 节点ID。
/// </summary>
public string id { get; set; }
/// <summary>
/// 父节点ID。
/// </summary>
public string pId { get; set; }
/// <summary>
/// 节点名称。
/// </summary>
public string name { get; set; }
/// <summary>
/// 是否展开。
/// </summary>
public bool open { get; set; }
/// <summary>
/// 是否选中。
/// </summary>
public bool @checked { get; set; }
}
}

View File

@@ -1,37 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace .Utility.Web
{
public class WithExtensionMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public string guid { get; set; }
public string OriginalName { get; set; }
public string Ext { get; set; }
public WithExtensionMultipartFormDataStreamProvider(string rootPath, string guidStr) : base(rootPath)
{
guid = guidStr;
}
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
{
OriginalName = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? GetValidFileName(headers.ContentDisposition.FileName) : "";
Ext = !string.IsNullOrWhiteSpace(OriginalName) ? Path.GetExtension(GetValidFileName(OriginalName)) : "";
return guid + Ext;
}
private string GetValidFileName(string filePath)
{
char[] invalids = System.IO.Path.GetInvalidFileNameChars();
return string.Join("_", filePath.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
}
}
}

View File

@@ -122,7 +122,10 @@ namespace 电子展板.ViewModels
/// </summary> /// </summary>
public void WindowClosing(CancelEventArgs args) public void WindowClosing(CancelEventArgs args)
{ {
WebServer.Stop();
GlobalVariable.WebServer?.Stop();
GlobalVariable.WebServer?.Dispose();
GlobalVariable.WebServer = null;
Screen[] screens = Screen.AllScreens; Screen[] screens = Screen.AllScreens;
if (screens.Length > 1) if (screens.Length > 1)
{ {

View File

@@ -1,4 +1,7 @@
using System; using Nancy;
using Nancy.Hosting.Self;
using Nancy.Json;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Linq; using System.Linq;
@@ -30,12 +33,15 @@ namespace 电子展板.ViewModels
this.window.Top = (int)(Screen.AllScreens[screenIndex].Bounds.Top / GetDpiScaleX()); this.window.Top = (int)(Screen.AllScreens[screenIndex].Bounds.Top / GetDpiScaleX());
this.window.Width = (int)(Screen.AllScreens[screenIndex].Bounds.Width / GetDpiScaleX()); this.window.Width = (int)(Screen.AllScreens[screenIndex].Bounds.Width / GetDpiScaleX());
this.window.Height = (int)(Screen.AllScreens[screenIndex].Bounds.Height / GetDpiScaleX()); this.window.Height = (int)(Screen.AllScreens[screenIndex].Bounds.Height / GetDpiScaleX());
WebServer.Start(); GlobalVariable.WebServer = new NancyHost(new Uri("http://localhost:80"));
GlobalVariable.WebServer.Start();
} }
private void WindowClosing(CancelEventArgs args) private void WindowClosing(CancelEventArgs args)
{ {
WebServer.Stop(); GlobalVariable.WebServer?.Stop();
GlobalVariable.WebServer?.Dispose();
GlobalVariable.WebServer = null;
Environment.Exit(0); Environment.Exit(0);
} }
public double GetDpiScaleX() public double GetDpiScaleX()

140
电子展板/WebModule.cs Normal file
View File

@@ -0,0 +1,140 @@
using Nancy;
using Nancy.Extensions;
using Nancy.ModelBinding;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using .Base;
using .Utility;
using .Utility.Core;
using .Utility.Extension;
using .Utility.Logs;
using .Utility.Other;
namespace
{
public class WebModule : NancyModule
{
public WebModule()
{
//默认页面
Get("", Index);
Get("/", Index);
Get("/index.html", Index);
//全局静态资源
Get("/static/{name*}", StaticResource);
//获得配置
Get("/getConfig", GetConfig);
//获得上传的文件
Get("/upload/{id}", GetUploadFiles);
//上传图片
Post("/uploadImage", UploadImage);
//保存配置
Post("/save", SaveConfig);
}
//默认页面
private object Index(dynamic dynamic)
{
return Resouce("Views/Index.html");
}
//全局静态资源
private object StaticResource(dynamic dynamic)
{
string name = dynamic.name;
return Resouce(name);
}
/// <summary>
/// 获得配置
/// </summary>
/// <param name="dynamic"></param>
/// <returns></returns>
private object GetConfig(dynamic dynamic)
{
//保留JSON KEY首字母大写这里就不用 Response.AsJson();
//AsJson会将首字母小写
return Response.AsText(JsonHelper.ToJson(GlobalVariable.Config), "application/json", Encoding.UTF8);
}
/// <summary>
/// 获得上传的文件
/// </summary>
/// <param name="dynamic"></param>
/// <returns></returns>
private object GetUploadFiles(dynamic dynamic)
{
string id = dynamic.id;
string contentType = System.Web.MimeMapping.GetMimeMapping(id);
return Response.AsFile(MyEnvironment.Root("/Upload/" + id), contentType);
}
/// <summary>
/// 上传图片
/// </summary>
/// <param name="dynamic"></param>
/// <returns></returns>
private object UploadImage(dynamic dynamic)
{
string uploadPath = MyEnvironment.Root("/Upload/");
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
List<string> filePathList = new List<string>();
foreach (var file in Request.Files)
{
string ext = Path.GetExtension(file.Name);
string fileName = UUID.StrSnowId + ext;
var filePath = uploadPath + fileName;
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
file.Value.CopyTo(fileStream);
}
filePathList.Add($"/Upload/{fileName}");
}
var result = new { state = 1, message = "上传成功", data = filePathList.GetStrArray() };
return Response.AsJson(result);
}
/// <summary>
/// 保存配置
/// </summary>
/// <param name="dynamic"></param>
/// <returns></returns>
private object SaveConfig(dynamic dynamic)
{
MyConfig config = this.Bind<MyConfig>();
//string str = Request.Body.AsString();
//MyConfig config = JsonHelper.ToObject<MyConfig>(str);
LogHelper.Instance.Info($"用户保存了配置:{JsonHelper.ToJson(config)}");
//保存
PropertyInfo[] propertyInfos = typeof(MyConfig).GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
object value = propertyInfo.GetValue(config);
propertyInfo.SetValue(GlobalVariable.Config, value);
}
GlobalVariable.SaveConfig();
//保存并修改界面
EventBus.Instance.Publish("save", "");
var result = new { state = 1, message = "保存成功" };
return Response.AsJson(result);
}
private object Resouce(string resourcePath)
{
string packUri = $"pack://application:,,,/Assets/{resourcePath}";
string contentType = System.Web.MimeMapping.GetMimeMapping(packUri);
return Response.FromStream(System.Windows.Application.GetResourceStream(new Uri(packUri, UriKind.RelativeOrAbsolute)).Stream, contentType);
}
}
}

View File

@@ -1,126 +0,0 @@
using Beginor.Owin.StaticFile;
using JinianNet.JNTemplate;
using Microsoft.Extensions.Configuration;
using Microsoft.Owin;
using Microsoft.Owin.Hosting;
using Owin;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Net.Mime;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using .Utility.Core;
using .Utility.Extension;
using .Utility.Logs;
using static System.Net.Mime.MediaTypeNames;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace
{
public class WebServer
{
private static IDisposable host;
public static void Start()
{
LogHelper.Instance.Info("正在开启Web服务");
StartOptions startOptions = new StartOptions();
startOptions.Urls.Add($"http://*:80/");
host = WebApp.Start<Startup>(startOptions);
}
public static void Stop()
{
if (host == null)
return;
LogHelper.Instance.Info("正在停止Web服务");
host.Dispose();
host = null;
}
}
/// <summary>
/// Web启动类
/// </summary>
public class Startup
{
private HttpConfiguration _config;
/// <summary>
/// 配置
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
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<ResouceStaticRoute>("/static", "/Assets");
app.UseWebApi(_config);
//配置模板引擎
Engine.Configure(c =>
{
c.TagPrefix = "${";
c.TagSuffix = "}";
c.TagFlag = '^';
});
}
}
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);
}
}
}
}

View File

@@ -31,21 +31,12 @@
<ItemGroup> <ItemGroup>
<!-- JSON框架 --> <!-- JSON框架 -->
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
<!-- 模板引擎 -->
<PackageReference Include="JinianNet.JNTemplate" Version="2.4.3" />
<!-- 日志框架 --> <!-- 日志框架 -->
<PackageReference Include="NLog" Version="6.0.2" /> <PackageReference Include="NLog" Version="6.0.2" />
<!-- WEB 自宿主 --> <!-- WEB 自宿主 -->
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="9.0.9" /> <Reference Include="System.Web" />
<PackageReference Include="Microsoft.AspNet.WebApi.Owin" version="5.3.0" /> <PackageReference Include="Nancy" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNet.WebApi.Core" Version="5.3.0" /> <PackageReference Include="Nancy.Hosting.Self" Version="2.0.0" />
<PackageReference Include="Microsoft.Owin" Version="4.2.3" />
<PackageReference Include="Microsoft.Owin.Host.SystemWeb" Version="4.2.3" />
<PackageReference Include="Microsoft.AspNet.WebApi.OwinSelfHost" Version="5.3.0" />
<PackageReference Include="Microsoft.AspNet.Identity.Owin" Version="2.2.4" />
<PackageReference Include="Swashbuckle.Core" version="5.6.0" />
<PackageReference Include="Beginor.Owin.StaticFile" Version="0.3.1" />
<PackageReference Include="Microsoft.AspNet.Mvc" Version="5.3.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Content Include="Upload\0.jpg"> <Content Include="Upload\0.jpg">