using BBWY.Common.Models; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BBWY.Server.API.Middlewares { public class ClientVersionValidationMiddleWare { /// /// 管道请求委托 /// private RequestDelegate _next; private IDictionary apiVersionDictionary; private IOptionsMonitor> _monitor; public ClientVersionValidationMiddleWare(RequestDelegate requestDelegate, IOptionsMonitor> monitor) { _next = requestDelegate; _monitor = monitor; apiVersionDictionary = new Dictionary(); } public async Task Invoke(HttpContext context) { try { Console.WriteLine(context.Request.Path); var apiRequirement = _monitor.CurrentValue.FirstOrDefault(x => x.Api.Equals(context.Request.Path, StringComparison.CurrentCultureIgnoreCase)); if (apiRequirement != null) { if (!context.Request.Headers.TryGetValue("ClientVersion", out StringValues clientVersionStr)) throw new BusinessException("未读取到ClientVersion"); if (!int.TryParse(clientVersionStr, out int clientVersion)) throw new BusinessException("非法ClientVersion"); if (clientVersion < apiRequirement.MinimumVersion) throw new BusinessException("当前ClientVersion低于接口最低要求,请升级到最新版"); } await _next(context); //调用管道执行下一个中间件 } catch { throw; } } } public class ClientVersionValidationModel { public string Api { get; set; } public int MinimumVersion { get; set; } } }