【问题标题】:How do you inject a scoped service into an implementation of IClaimsTransformer?如何将范围服务注入 IClaimsTransformer 的实现?
【发布时间】:2016-06-10 11:30:18
【问题描述】:

ASP.Net 核心允许您使用 IClaimsTransformer 的实现来修改 ClaimsPrincipal。我了解到您是这样注册的:

app.UseClaimsTransformation(o => o.Transformer = new MyClaimsTransformer());

但在 MyClaimsTransformer 中,我需要访问我的数据库。我的问题是如何注入或访问在 MyClaimsTransformer 内提供数据访问的范围服务?

【问题讨论】:

  • 您需要什么范围?请求范围还是自定义范围?
  • @Dovydas Navickas 我需要请求范围,因为我想获取一个使用实体框架的存储库服务,并且我想确保它在请求结束时被释放。

标签: asp.net asp.net-core asp.net-core-mvc .net-core


【解决方案1】:

@dovydas-navickas 的答案中链接的问题现已解决。

在 ASP.NET Core 1.0-RC2 中,接口 IClaimsTransformer 已更新为采用 ClaimsTransformationContext,它提供了一种通过 HttpContext 访问服务的方式。

例如,如果您需要访问内存缓存,可以像这样检索它

public Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext context)
{
    IMemoryCache cache = context.Context.RequestServices.GetService<IMemoryCache>();

    // ... the rest of the implementation.
}

【讨论】:

    【解决方案2】:

    我认为目前是不可能的。

    你正在使用的方法的实现可以在here找到

    public static IApplicationBuilder UseClaimsTransformation(this IApplicationBuilder app, Func<ClaimsPrincipal, Task<ClaimsPrincipal>> transform)
    {
        if (app == null)
        {
            throw new ArgumentNullException(nameof(app));
        }
        if (transform == null)
        {
            throw new ArgumentNullException(nameof(transform));
        }
    
        return app.UseClaimsTransformation(new ClaimsTransformationOptions 
        {
            Transformer = new ClaimsTransformer { OnTransform = transform }
        });
    }
    

    如您所见,它是一种简单的代理方法,仅提供ClaimsTransformationOptions 属性Transformer

    而当您只获得ClaimsPrincipal 时,您无法访问它的请求。

    可能是您提交了此问题,但如果不是,您可以跟踪它here

    【讨论】:

    • 是的,我不确定这是设计中的疏忽还是我遗漏了什么,因为在我看来,如果没有注入,您将无法进行任何有意义的声明转换,因为您没有无法访问您的数据。
    • 介意接受答案,因为它暂时是正确的。有变化我会更新的。
    • RC1 很难理解没有人考虑过如何处理这种情况。如果到下周末没有解决方案,我会接受你的回答。
    猜你喜欢
    • 2017-03-20
    • 2020-12-30
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 2019-08-22
    • 1970-01-01
    相关资源
    最近更新 更多