How to register a default user at the beginning of the application?

Asked

Viewed 94 times

2

In an ASP.Net MVC application I need to have a default user record and for that I am thinking of adding it on startup of the application.

In the archive Global.asax I did the following:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        // Registradores ...

        // Comando para setar os registros básicos
        App_Start.DatabaseConfig.SetDataDefault(); 
    }
}

And in class DataBaseConfig I have:

public static void SetDataDefault()
{
    using (var ctx = new Data.Context.ApplicationDbContext())
    {
        // Outras adições simples ...

        if (!ctx.Users.Any())
        {
            // Adiciona o usuário padrão
            ... // Oo heim.. !!??
        }
    }
}

How to proceed to add a user at this time, judging that I need to get an instance of ApplicationUserManager to register the user?

1 answer

2

In fact, it’s quite simple, it was just missing a little more research.

The question was only to know how to instill the class ApplicationUserManager, and it’s not complicated, just follow the requested parameters.

Anyway, with this I could register the user:

if (!ctx.Users.Any())
{
    using(var manager = new ApplicationUserManager(new UserStore<Model.User>(ctx)))
    {
        manager.Create(new Model.User
        {
            EmailConfirmed = true,
            UserName = "nome de usuário",
            Email = "[email protected]"
        }, "AQUI VAI A SENHA");

        ctx.SaveChanges();
    }
}

Whereas ApplicationUserManager is already a class created by the Visual Studio template with the option Individual User Account selected.

She is declared so:

public class ApplicationUserManager : UserManager<Model.User>
{
    ....
}

Soon, I could have instilled a class of the kind Usermanager thus:

var manager = new UserManager<Model.User>(new UserStore<Model.User>(ctx));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.