105040 Update 添加中间件支持

This commit is contained in:
lihanbo 2024-10-31 10:38:21 +08:00
parent 9574d7e0b6
commit ae37631d03
11 changed files with 163 additions and 4 deletions

View File

@ -1,3 +1,5 @@
using System.Reflection;
namespace LFlow.Base;
/// <summary>
/// 程序对象
@ -10,4 +12,6 @@ public class App
{
return ServiceProvider!.GetService<T>();
}
public static List<Assembly> SubServiceAssembly = [];
}

View File

@ -27,4 +27,8 @@
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LFlow.Middleware\LFlow.Middleware.csproj" />
</ItemGroup>
</Project>

View File

@ -1,5 +1,7 @@
using LFlow.Base.Interfaces;
using LFlow.Base.Utils;
using LFlow.Middleware;
using LFlow.Middleware.Register;
using Serilog;
using Serilog.Events;
using SqlSugar;
@ -29,9 +31,11 @@ public static class Program
builder.Services.AddResponseCompression();
builder.Services.AddResponseCaching();
Log.Logger.Information("LoadSubService");
builder.Services.LoadSubService();
builder.Services.RegisterMiddlewares(App.SubServiceAssembly);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddHttpContextAccessor();
@ -75,6 +79,7 @@ public static class Program
// .WriteTo.Console();
}, true);
// init App.service
App.services = builder.Services;
var app = builder.Build();
app.UseSerilogRequestLogging(options =>
@ -104,6 +109,8 @@ public static class Program
Log.Logger.Information("ApplicationStarted");
CodeFirst.InitTable();
});
// 启用自定义中间件
app.UseLFlowMiddleware();
// 启用缓存
app.UseResponseCaching();
@ -159,6 +166,7 @@ public static class Program
{
try
{
bool isModule = false;
Log.Logger.Information($"Load file -> {file}...");
var assembly = Assembly.LoadFile(file);
var types = assembly.GetTypes();
@ -174,6 +182,7 @@ public static class Program
Log.Logger.Information($"\tFound IModule -> {type.FullName}");
var module = Activator.CreateInstance(type) as IModule;
module?.ConfigureModule(services);
isModule = true;
}
}
}
@ -183,6 +192,10 @@ public static class Program
// // 添加Controller
// services.AddControllers().AddApplicationPart(assembly);
// }
if (isModule)
{
App.SubServiceAssembly.Add(assembly);
}
Log.Logger.Information("done.\r\n");
}
catch (Exception ex)

View File

@ -0,0 +1,20 @@
using Microsoft.AspNetCore.Http;
namespace LFlow.Middleware
{
public interface IMiddleware
{
/// <summary>
/// 优先级
/// </summary>
int Priority { get; }
/// <summary>
/// 入口
/// </summary>
/// <param name="context"></param>
/// <param name="next"></param>
/// <returns></returns>
Task RunAsync(HttpContext context, Func<Task> next);
}
}

View File

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,19 @@
using LFlow.Middleware.Register;
using Microsoft.AspNetCore.Builder;
namespace LFlow.Middleware
{
public static class MiddlewareExtensions
{
/// <summary>
/// Use LFlow Middleware
/// 配置中间件
/// </summary>
/// <param name="app"></param>
public static async void UseLFlowMiddleware(this IApplicationBuilder app)
{
app.BuildMiddlewareServiceProvider();
await MiddlewareRegister.Handle(app);
}
}
}

View File

@ -0,0 +1,54 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
namespace LFlow.Middleware.Register
{
public static class MiddlewareRegister
{
private static IServiceProvider _serviceProvider;
private static readonly IDictionary<Type, IMiddleware> _middlewares = new Dictionary<Type, IMiddleware>();
private static List<Type> _middlewareTypes = [];
public static void RegisterMiddlewares(this IServiceCollection service, List<Assembly> assemblys)
{
//var assembly = Assembly.getas()!;
assemblys.ForEach(assembly =>
{
var types = assembly.GetTypes().ToList();
foreach (var type in types)
{
if (type.GetInterface(nameof(IMiddleware)) != null)
{
service.AddSingleton(type);
_middlewareTypes.Add(type);
}
}
});
}
public static void BuildMiddlewareServiceProvider(this IApplicationBuilder application)
{
_serviceProvider = application.ApplicationServices;
_middlewareTypes.ForEach(type =>
{
if (_serviceProvider.GetService(type) is IMiddleware middleware)
_middlewares.Add(type, middleware);
});
}
/// <summary>
/// 处理中间件
/// </summary>
/// <param name="context"></param>
/// <param name="next"></param>
/// <returns></returns>
public static async Task Handle(IApplicationBuilder application)
{
var orderedMiddlewares = _middlewares.Values.OrderBy(m => m.Priority).ToList();
foreach (var middleware in orderedMiddlewares)
{
application.Use(middleware.RunAsync);
}
}
}
}

View File

@ -3,15 +3,22 @@ using LFlow.Base.Utils;
using LFlow.UserManagement.Model;
using LFlow.UserManagement.Service;
using Microsoft.AspNetCore.Mvc;
using Serilog;
namespace LFlow.UserManagement.Controller
{
public class UserManagementController(IUserManagementService service) : BaseController
public class UserManagementController(IUserManagementService service, ILogger logger) : BaseController
{
[HttpPost]
public ApiResult<UserDto>? Login(UserDto user)
{
return Success(service.Login(user));
var loginedUser = service.Login(user);
if (loginedUser == null)
{
logger.Error("登录失败,用户名或密码错误");
return Fail(loginedUser, "登录失败,用户名或密码错误", 10001);
}
return Success(loginedUser);
}
[HttpPost]
public ApiResult<UserDto> Register(UserDto user)

View File

@ -20,7 +20,7 @@ namespace LFlow.UserManagement.Service
UserPassword = userPwd
});
if (userModel == null)
if (userModel == null || !userModel.Any())
{
return null;
}

View File

@ -0,0 +1,18 @@
using LFlow.Middleware;
using Serilog;
namespace LFlow.UserManagement
{
public class UserMiddleware(ILogger logger) : IMiddleware
{
public int Priority => 1;
public async Task RunAsync(Microsoft.AspNetCore.Http.HttpContext context, Func<Task> next)
{
// Do something before
var path = context.Request.Path;
logger.Information(path);
await next();
// Do something after
}
}
}

View File

@ -9,7 +9,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LFlow.VersionManagement", "
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LFlow.OnlineManegement", "LFlow.OnlineManegement\LFlow.OnlineManegement.csproj", "{E849310F-64AD-453A-A2AA-557731508BF1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LFlow.UserManagement", "LFlow.UserManagement\LFlow.UserManagement.csproj", "{DA68CE22-AC53-40BD-AB2A-5C52DFDDD548}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LFlow.UserManagement", "LFlow.UserManagement\LFlow.UserManagement.csproj", "{DA68CE22-AC53-40BD-AB2A-5C52DFDDD548}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LFlow.Middleware", "LFlow.Middleware\LFlow.Middleware.csproj", "{5BFD207E-28B3-40B8-94DF-1723C6A4424B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -33,6 +35,10 @@ Global
{DA68CE22-AC53-40BD-AB2A-5C52DFDDD548}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DA68CE22-AC53-40BD-AB2A-5C52DFDDD548}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DA68CE22-AC53-40BD-AB2A-5C52DFDDD548}.Release|Any CPU.Build.0 = Release|Any CPU
{5BFD207E-28B3-40B8-94DF-1723C6A4424B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5BFD207E-28B3-40B8-94DF-1723C6A4424B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5BFD207E-28B3-40B8-94DF-1723C6A4424B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5BFD207E-28B3-40B8-94DF-1723C6A4424B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE