在自定义过滤器.net Core中使用依赖注入始终为null

时间:2018-10-05 07:43:38

标签: c# asp.net-core dependency-injection

当我在TokenAuthorizeFilter中使用DI时,_User始终返回null。不仅仅是_User,这只是我遇到的一个例子。我尝试了不同的方法,但仍然无法正常工作。

我现在很困惑,请告诉我为什么。谢谢

public class BaseAuthorizeFilter : IAuthorizationFilter, IActionFilter
{
    public static ClaimsIdentity _User;
    public static IHttpContextAccessor _accessor;

    public BaseAuthorizeFilter(UserResolverService userService, IHttpContextAccessor accessor)
    {
        _User = userService.GetUser();
        _accessor = accessor;
    }
}
...

UserResolverService.cs

public class UserResolverService : IUserResolverService
{
    private readonly IHttpContextAccessor _context;

    public UserResolverService(IHttpContextAccessor context)
    {
        _context = context;
    }

    public ClaimsIdentity GetUser()
    {
        return _context.HttpContext.User.Identity as ClaimsIdentity;
        //await
    }
}

public interface IUserResolverService
{
    ClaimsIdentity GetUser();
}

TokenAuthorizeFilter.cs

public class TokenAuthorizeFilter : BaseAuthorizeFilter
{
    var identity = _User;
}

对不起,我没有在问题中提及任何内容。我正在从另一个类调用TokenAuthorizeFilter中的方法,因此我将其定义为静态。现在,我改变了编写方式,并从Microsoft网站上找到了答案。非常感谢。

https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-2.1#ifilterfactory-implemented-on-your-attribute

1 个答案:

答案 0 :(得分:0)

您的帖子中有多个问题。

  • 您通过IUserResolverService注册了services.AddSingleton<IUserResolverService, UserResolverService>();,但是您注入了UserResolverService userService
  • 您不应将ClaimsIdentity _User定义为静态,而应将其隔离为请求

尝试如下更改:

    public class BaseAuthorizeFilter : IAuthorizationFilter, IActionFilter
{
    public ClaimsIdentity _User;
    public IHttpContextAccessor _accessor;

    public BaseAuthorizeFilter(IUserResolverService userService, IHttpContextAccessor accessor)
    {
        _User = userService.GetUser();
        _accessor = accessor;
    }
  • 检查您的TokenAuthorizeFilter与以下代码之间的区别:

    public class TokenAuthorizeFilter : BaseAuthorizeFilter
    {
       public TokenAuthorizeFilter(IUserResolverService userService
           , IHttpContextAccessor accessor):base(userService, accessor)
      {
          var identity = _User;
      }
    }
    
  • TokenAuthorizeFilter注册为AddScoped

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddSingleton<IUserResolverService, UserResolverService>();
        services.AddScoped<TokenAuthorizeFilter>();