优化功能,新增全局过滤实现静态资源加载

This commit is contained in:
2025-09-22 17:19:34 +08:00
parent 01774452cb
commit 9a89a138dd
5 changed files with 78 additions and 233 deletions

View File

@@ -1,19 +1,28 @@
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
@@ -57,6 +66,8 @@ namespace 电子展板
_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 =>
@@ -67,4 +78,49 @@ namespace 电子展板
});
}
}
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);
}
}
}
}