我正在.net核心中创建自定义授权。一切工作都很好,但是我想在属性响应中添加本地化器。
下面是我的代码
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class CustomAuthorizeFilters : AuthorizeAttribute, IAuthorizationFilter
{
public CustomAuthorizeFilters()
{ }
public void OnAuthorization(AuthorizationFilterContext context)
{
var User = context.HttpContext.User;
if (!User.Identity.IsAuthenticated)
return;
using (var account_help = new AccountHelpers(Startup.ConnectionString))
{
var userId = Guid.Parse(new security.AesAlgoridhm().Decrypt(User.Claims.Where(x => x.Type == JwtRegisteredClaimNames.Sid)?.FirstOrDefault().Value));
ProfileResponse user = new ProfileResponse();
if (user == null)
context.Result = new CustomResultFilters("error_access_token_expired", 401);
if (!user.EmailConfirmed)
context.Result = new CustomResultFilters("bad_response_account_not_confirmed", 400);
if (!user.Active)
context.Result = new CustomResultFilters("bad_response_account_inactive", 400);
}
}
}
我试图像这样在构造函数中传递本地化器,但是当我从控制器传递参数时,它给我的错误是
属性构造函数参数的类型不是有效的属性参数类型
IStringLocalizer<dynamic> localize { get; set; }
public CustomAuthorizeFilters(IStringLocalizer<dynamic> localizer = null)
{
localize = localizer;
}
我知道属性仅支持原始数据类型,这就是为什么我也尝试将直接依赖项注入为
context.HttpContext.RequestServices.GetService(typeof(IStringLocalizer<dynamic>));
但这会产生错误,因为无法从对象转换到本地化器。
任何帮助将不胜感激。
答案 0 :(得分:0)
您可以使用shared资源并像这样获得本地化程序
Type localizerType = typeof(IStringLocalizer<SharedResource>);
IStringLocalizer localizer = (IStringLocalizer)context.HttpContext.RequestServices.GetService(localizerType );
或者,如果您正在使用每个控制器的资源,则可以从context
获取控制器类型并获取控制器本地化程序
public void OnAuthorization(AuthorizationFilterContext context)
{
//..
Type localizerType = GetLocalizerType(context);
IStringLocalizer localizer = (IStringLocalizer)context.HttpContext.RequestServices.GetService(localizerType);
//..
}
private Type GetLocalizerType(AuthorizationFilterContext context)
{
var controllerType = (context.ActionDescriptor as ControllerActionDescriptor).ControllerTypeInfo;
return typeof(IStringLocalizer<>).MakeGenericType(controllerType);
}