6 changed files with 76 additions and 4 deletions
@ -0,0 +1,55 @@ |
|||||
|
using BBWYB.Common.Models; |
||||
|
using Microsoft.Extensions.Options; |
||||
|
using Microsoft.Extensions.Primitives; |
||||
|
|
||||
|
namespace BBWYB.Server.API.Middlewares |
||||
|
{ |
||||
|
public class ClientVersionValidationMiddleWare |
||||
|
{ |
||||
|
/// <summary>
|
||||
|
/// 管道请求委托
|
||||
|
/// </summary>
|
||||
|
private RequestDelegate _next; |
||||
|
|
||||
|
private IDictionary<string, int> apiVersionDictionary; |
||||
|
|
||||
|
private IOptionsMonitor<List<ClientVersionValidationModel>> _monitor; |
||||
|
|
||||
|
public ClientVersionValidationMiddleWare(RequestDelegate requestDelegate, IOptionsMonitor<List<ClientVersionValidationModel>> monitor) |
||||
|
{ |
||||
|
_next = requestDelegate; |
||||
|
_monitor = monitor; |
||||
|
apiVersionDictionary = new Dictionary<string, int>(); |
||||
|
} |
||||
|
|
||||
|
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; } |
||||
|
} |
||||
|
} |
Loading…
Reference in new issue