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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ApplicationUser在Asp.Net Core 2.0中的ActionFilter中?相关的知识,希望对你有一定的参考价值。

如何在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());
    });
...
答案

尝试在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" }));
            }
            ...
        }
    }
}

以上是关于ApplicationUser在Asp.Net Core 2.0中的ActionFilter中?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 ASP.Net MVC 5 视图中获取 ApplicationUser 的自定义属性值?

ASP.NET Core 标识不注入 UserManager<ApplicationUser>

从 asp.net 核心标识中获取 applicationuser 的属性

从 ASP.net Core 2 中的视图访问自定义 ApplicationUser 属性

ASP.NET Core Identity UserManager<ApplicationUser> -Error 没有为此对象定义无参数构造函数

ASP.NET MVC 如何使用 ApplicationUser 和其他域类之间的多对多关系