gpt4 book ai didi

c# - 没有构造函数的本地化依赖注入(inject)

转载 作者:太空宇宙 更新时间:2023-11-03 14:43:46 24 4
gpt4 key购买 nike

我正在 .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);
}
}
}

我试过像这样在构造函数中传递定位器,但是当我从 Controller 传递一个参数时,它给我的错误是

attribute constructor parameter has type which is not a valid attribute parameter type

  IStringLocalizer<dynamic> localize { get; set; }
public CustomAuthorizeFilters(IStringLocalizer<dynamic> localizer = null)
{
localize = localizer;
}

我知道属性只支持原始数据类型,这就是为什么我也尝试注入(inject)直接依赖作为

context.HttpContext.RequestServices.GetService(typeof(IStringLocalizer<dynamic>));

但这是错误的:

cannot convert from object to localizer.

最佳答案

您可以使用 shared资源并像这样获得本地化器

Type localizerType = typeof(IStringLocalizer<SharedResource>);
IStringLocalizer localizer = (IStringLocalizer)context.HttpContext.RequestServices.GetService(localizerType );

或者,如果您使用每个 Controller 的资源,您可以从 context 获取 Controller 类型并获取 Controller 定位器

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);
}

关于c# - 没有构造函数的本地化依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55509864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com