如何访问Asp.Net Core 2.0中ApplicationUser
内的当前UserManager
(或ActionFilter
)?
我试图锁定整个应用程序,直到用户接受EULA(最终用户许可协议),更改其密码并填写所需的个人信息。
public class ApplicationUser : IdentityUser
{
...
public DateTime? DateEULAAccepted { get; set; }
...
}
以下是ActionFilter
代码:
public class ProfileRequiredActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
var CurUser = UserManager<ApplicationUser>.GetUserAsync(filterContext.HttpContext.User);
...
if (CurUser.Result.DateEULAAccepted.ToString() == null)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Account", action = "AgreeToEULA" }));
}
...
}
}
}
我正在ActionFilter
中实例化Startup > ConfigureServices
,如下所示:
...
services.AddMvc(options =>
{
options.Filters.Add(new ProfileRequiredActionFilter());
});
...
答案 0 :(得分:4)
尝试在ConfigureServices()
中添加过滤器,如下所示:
services.AddMvc(options => {
options.Filters.Add<ProfileRequiredActionFilter>();
});
然后,您可以按如下方式将UserManager
注入过滤器:
public class ProfileRequiredActionFilter : IActionFilter
{
private UserManager<ApplicationUser> _userManager;
public ProfileRequiredActionFilter(UserManager<ApplicationUser> userManager)
{
_userManager = userManager
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
var CurUser = _userManager<ApplicationUser>.GetUserAsync(filterContext.HttpContext.User);
...
if (CurUser.Result.DateEULAAccepted.ToString() == null)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Account", action = "AgreeToEULA" }));
}
...
}
}
}