\ApeVolo.Api\ActionExtension\Sign\VerifySignatureAttribute.cs
huster-songtao opened this issue · comments
// ...
var redisCacheService = AutofacHelper.GetService<IRedisCacheService>();
// ...
// ...
var appSecretModel = await AutofacHelper.GetService<IAppSecretService>()
.QueryFirstAsync(x => x.IsDeleted == false && x.AppId == appId);
// ...
VerifySignatureAttribute是Attribute,注入有几种办法,参考下面链接
https://www.andybutland.dev/2020/06/dependency-injection-in-aspnet-core-attributes.html
最简单的就是直接用ActionExecutingContext filterContext
var redisCacheService = filterContext.HttpContext.RequestServices.GetRequiredService<IRedisCacheService>();
var appSecretModel = await filterContext.HttpContext.RequestServices.GetRequiredService<IAppSecretService>().FirstAsync(x => x.IsDeleted == false && x.AppId == appId);
对于 TokenFilterAttribute.cs
//private readonly IHttpContextAccessor _accessor = AutofacHelper.GetService<IHttpContextAccessor>();
//private readonly ICurrentUser _currentUser = AutofacHelper.GetService<ICurrentUser>();
public override async Task OnActionExecuting(ActionExecutingContext context)
{
try
{
var accessor = context.HttpContext.RequestServices.GetRequiredService<IHttpContextAccessor>();
var currentUser = context.HttpContext.RequestServices.GetRequiredService<ICurrentUser>();
下面基于TypeFilterAttribute的定义技巧我觉得也不错,这样将过滤器用于给定的控制器或操作方法不过于冗长
对这个感兴趣,可以阅读下文中的链接。
public class AddRandomNumberHeader2Attribute : TypeFilterAttribute
{
public AddRandomNumberHeader2Attribute() : base(typeof(AddRandomNumberHeader2Filter))
{
}
private class AddRandomNumberHeader2Filter : IResultFilter
{
private readonly IRandomNumberService _randomNumberService;
public AddRandomNumberHeader2Filter(IRandomNumberService randomNumberService)
{
_randomNumberService = randomNumberService;
}
public void OnResultExecuted(ResultExecutedContext context)
{
}
public void OnResultExecuting(ResultExecutingContext context)
{
context.HttpContext.Response.Headers.Add("X_Random_Number_3", _randomNumberService.GetRandomInteger().ToString());
}
}
}
[AddRandomNumberHeader2]
public IActionResult Index()
{
return Content("Hello world.");
}
@huster-songtao 感谢你的提议,代码已优化