4 changed files with 76 additions and 36 deletions
@ -0,0 +1,60 @@ |
|||
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 |
|||
{ |
|||
/// <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