在.net Core框架中添加具有管理员角色的超级用户 [英] Adding super user with admin role in .net core framework

查看:95
本文介绍了在.net Core框架中添加具有管理员角色的超级用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在尝试在ASP.Net Core Web应用程序中添加具有管理员角色的超级用户.我想在启动时添加此用户,我花了一些时间研究该主题,但没有成功.sartup看起来非常标准,开箱即用,如下所示:

currently I'm trying to add a super User with Admin role in ASP.Net Core web app. I want to add this user at startup, I spend some time researching about the subject without any success. The sartup looks very standard and out of the box as follows

 public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

        if (env.IsDevelopment())
        {
            // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
            builder.AddUserSecrets();

            // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
            builder.AddApplicationInsightsSettings(developerMode: true);
        }

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();

    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddApplicationInsightsTelemetry(Configuration);

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc();

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseApplicationInsightsRequestTelemetry();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseApplicationInsightsExceptionTelemetry();

        app.UseStaticFiles();

        app.UseIdentity();

        // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

这如何实现?

推荐答案

将参数 ApplicationDbContext dbContext 添加到 Configure 方法中-依赖项注入将创建适当的对象,您可以查找/添加所需的用户:

Add parameter ApplicationDbContext dbContext into Configure method - dependency injection will create appropriate object and you can Find/Add required users:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
    ILoggerFactory loggerFactory, ApplicationDbContext dbContext)
{
    ...

    if (dbContext.Users.Find(x => Name == "superadmin") == null)
    {
        db.Users.Add(new User { Name = "superadmin", ... });
        db.SaveChanges();
    }
}

或者您可以在参数中添加 UserManager 并将其用于用户操纵.

Or you may add UserManager into parameters and use it for users manipulation.

这篇关于在.net Core框架中添加具有管理员角色的超级用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆