2017-01-25 3 views
0

에서 관리 역할을 가진 수퍼 유저 추가 현재 ASP.Net 핵심 웹 애플리케이션에서 관리자 역할을 가진 수퍼 유저를 추가하려고합니다. 시작시이 사용자를 추가하고 싶습니다. 주제에 대해 조사하지 않고 시간을 할애합니다. sartup은 매우 표준 외모와 상자 밖으로이 달성 할 수있는 방법.net 핵심 프레임 워크

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?}"); 
     }); 
    } 

다음과 같이? Configure 방법에

+0

Startup 클래스는 사용자가 먼저 로그인해야하기 때문에 좋지 않습니다. 이를 처리하는 가장 좋은 방법은 AccountController의 로그인 액션입니다. –

+0

안녕하세요, 제안 주셔서 감사합니다. 나는이 사용자가 수퍼 유저가되어 관리자가 알고 있기 때문에 시작할 때이 파일을 필요로하며 이미 데이터베이스에 있어야하며 거기에 추가 할 파일이 없을 경우이 파일이 필요합니다. 그래서 로그인 할 때이 사용자를 사용하십시오. 이것을 어떻게 달성 할 수 있는지 예를 들려 줄 수 있습니까? –

답변

0

추가 매개 변수 ApplicationDbContext dbContext - 의존성 주입이 적절한 객체를 생성하고 당신이 필요한 사용자를 찾기/추가 할 수 있습니다

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를 추가하고 사용자 조작에 사용할 수 있습니다.

+0

제안 해 주셔서 감사합니다. 관리자를 위해 알려진 관리자 권한을 가진 사용자를 추가해야하며 하드 코드 된 것입니다. 귀하의 코드는 단지 사용자를 추가합니다 .. –

+0

나는 앱 시작 중에 데이터베이스에 데이터를 추가하는 방법을 제공합니다. 필요에 따라 역할, 클레임 등을 포함한 모든 데이터를 추가 할 수 있습니다. – Dmitry

+0

사실 그것은 완벽하게 작동했습니다. 힌트를 가져 주셔서 감사합니다. –