ApplicationUser在Asp.Net Core 2.0中的ActionFilter中?

时间:2017-12-19 20:18:41

标签: entity-framework asp.net-core-mvc asp.net-core-2.0

如何访问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());
    });
...

1 个答案:

答案 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" }));
            }
            ...
        }
    }
}