【问题标题】:Get the UserManager instance outside of ASP.NET web application?在 ASP.NET Web 应用程序之外获取 UserManager 实例?
【发布时间】:2018-08-10 19:55:35
【问题描述】:

我有一个带有 ASP.NET 身份(个人帐户)的 ASP.NET MVC 5 Web 应用程序。但我需要能够从控制台应用注册新用户。

所以我将一些 ASP.NET Identity 类从 Web 应用程序移到一个类库中,以便在 Web 应用程序和 CLI 之间共享。

我已成功移动以下内容:

public class PortalDbContext : IdentityDbContext<PortalUser>
{
    public PortalDbContext(string connectionString)
        : base(connectionString, throwIfV1Schema: false)
    {
    }

    public static PortalDbContext Create(string connectionString)
    {
        return new PortalDbContext(connectionString);
    }
}

public class PortalUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<PortalUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

        // Add custom user claims here
        return userIdentity;
    }
}

public class PortalUserManager : UserManager<PortalUser>
{
    public PortalUserManager(IUserStore<PortalUser> store) : base(store)
    {
    }

    public async Task<IdentityResult> RegisterUser(string email, string password)
    {
        PortalUser user = new PortalUser { UserName = email, Email = email };

        return await this.CreateAsync(user, password);
    }
}

但我不知道从哪里获得 IUserStore&lt;PortalUser&gt;PortalUserManager 的需求。

在网络应用程序中,这个管理器是从 HttpContext.GetOwinContext().GetUserManager&lt;ApplicationUserManager&gt;() 检索到的,我显然不能在类库中使用它。

【问题讨论】:

    标签: c# asp.net asp.net-identity asp.net-identity-2


    【解决方案1】:

    看看OwinRequestScopeContext nuget 包。它允许您使用不依赖于System.Web 的上下文。为了没有仅链接的答案,我将添加当前自述文件中的示例:

    # Usage 
    
    // using Owin; you can use UseRequestScopeContext extension method.
    
    // enabled timing is according to Pipeline.
    // so I recommend enable as far in advance as possible.
    app.UseRequestScopeContext();
    
    app.UseErrorPage();
    app.Run(async _ =>
    {
        // get global context like HttpContext.Current.
        var context = OwinRequestScopeContext.Current;
    
        // Environment is raw Owin Environment as IDictionary<string, object>.
        var __ = context.Environment;
    
        // optional:If you want to change Microsoft.Owin.OwinContext, you can wrap.
        new Microsoft.Owin.OwinContext(context.Environment);
    
        // Timestamp is request started(correctly called RequestScopeContextMiddleware timing).
        var ___ = context.Timestamp;
    
        // Items is IDictionary<string, object> like HttpContext.Items.
        // Items is threadsafe(as ConcurrentDictionary) by default.
        var ____ = context.Items;
    
        // DisposeOnPipelineCompleted can register dispose when request completed(correctly RequestScopeContextMiddleware underling Middlewares finished)
        // return value is cancelToken. If call token.Dispose() then canceled register.
        var cancelToken = context.DisposeOnPipelineCompleted(new TraceDisposable());
    
        // OwinRequestScopeContext over async/await also ConfigureAwait(false)
        context.Items["test"] = "foo";
        await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false);
        var _____ = OwinRequestScopeContext.Current.Items["test"]; // foo
    
        await Task.Run(() =>
        {
            // OwinRequestScopeContext over new thread/threadpool.
            var ______ = OwinRequestScopeContext.Current.Items["test"]; // foo
        });
    
        _.Response.ContentType = "text/plain";
        await _.Response.WriteAsync("Hello OwinRequestScopeContext! => ");
        await _.Response.WriteAsync(OwinRequestScopeContext.Current.Items["test"] as string); // render foo
    });
    

    【讨论】:

    • 这对于我的需要来说似乎过于复杂。我只是想知道如何实例化UserStore
    【解决方案2】:

    我最终添加了一个静态方法 Create(string connectionString)PortalUserManager,它将创建 UserStoreDbContext 并返回一个新的管理器实例。

    public class PortalDbContext : IdentityDbContext<PortalUser>
    {
        public PortalDbContext(string connectionString)
            : base(connectionString, throwIfV1Schema: false)
        {
        }
    
        public static PortalDbContext Create(string connectionString)
        {
            return new PortalDbContext(connectionString);
        }
    }
    
    public class PortalUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<PortalUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
    
            // Add custom user claims here
            return userIdentity;
        }
    }
    
    public class PortalUserManager : UserManager<PortalUser>
    {
        public PortalUserManager(IUserStore<PortalUser> store) : base(store)
        {
        }
    
        public static PortalUserManager Create(string connectionString)
        {
            UserStore<PortalUser> userStore = new UserStore<PortalUser>(PortalDbContext.Create(connectionString));
    
            PortalUserManager manager = new PortalUserManager(userStore);
    
            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator<PortalUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = true,
                RequireUniqueEmail = true                
            };
    
            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true,
            };
    
            return manager;
        }
    
        public async Task<IdentityResult> RegisterUser(string email, string password)
        {
            PortalUser user = new PortalUser { UserName = email, Email = email };
    
            return await this.CreateAsync(user, password);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-10
      • 2010-11-26
      • 2015-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多