当我在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网站上找到了答案。非常感谢。
答案 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>();