简体   繁体   中英

Trouble connecting ASP.NET MVC Core 2.0 with Entity Framework

I have a very simple web application, where I try to let people register a user. Therefore, I try to save user-registration data to Entity Framework, but with no luck.

I have a basic model and a basic view, so for the sake of brevity I am not going to post them as of right now, as I don't think the problem lies within them. If anybody would like to see them, I will post them. I am trying to make use of app.UseAuthentication and my guess is that some of my logic is wrong. I am trying to save to the table dbo.AspNetUsers .

Startup.cs

    public Startup(IHostingEnvironment env)
    {
        configuration = new ConfigurationBuilder()
                            .AddEnvironmentVariables()
                            .AddJsonFile(env.ContentRootPath + "/appsettings.json")
                            .Build();
    }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<IdentityDataContext>(options =>           
        options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<IdentityUser, IdentityRole>()
                                        .AddEntityFrameworkStores<IdentityDataContext>()
                                        .AddDefaultTokenProviders();
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            routes.MapRoute("Default", "{controller=Account}/{action=Index}");
        });

        app.UseFileServer();   
    }

appsettings.json

{
    "ConnectionStrings": {
        "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyLocalDB;Trusted_Connection=True;"
    }
}

Controller

public class AccountController : Controller
{
    public IActionResult Index()
    {
        return View(new CombinedLoginAndRegisterModel());
    }

    private readonly UserManager<IdentityUser> _userManager;
    private readonly SignInManager<IdentityUser> _signInManager;

    public AccountController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
    {
        _userManager = userManager;
        _signInManager = signInManager;
    }

    //Registration
    [HttpPost]
    public async Task<IActionResult> RegisterUser(CombinedLoginAndRegisterModel cbr)
    {
        var user = new IdentityUser
        {
            Email = cbr.Register.Email
        };

        var result = await _userManager.CreateAsync(user, cbr.Register.Password); //wait

        return View();
    }
}

Data Context

public class IdentityDataContext : IdentityDbContext<IdentityUser>
{
    public IdentityDataContext(DbContextOptions<IdentityDataContext> options) : base(options)
    {
        Database.EnsureCreated();
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }

}

I appreciate any help greatly and will respond to requests/comments.

EDIT

Index.cshtml

@model CS_config.Models.CombinedLoginAndRegisterModel

<h2>Register account</h2>

@using (Html.BeginForm())
{
    @Html.ValidationSummary()

    @Html.LabelFor(x => x.Register.Email, new { style = "margin-right: 7px;" })
    @Html.TextBoxFor(x => x.Register.Email)<br><br>

    @Html.LabelFor(x => x.Register.Password, new { style = "margin-right: 10px;" })
    @Html.TextBoxFor(x => x.Register.Password)<br><br>

    <button type="submit" name="RegisterUser">Submit</button> //named it to match the Task `RegisterUser` in the Controller
}

So I eventually found out a bunch of problems and why it didn't work. One thing I hadn't done was to do an initial migration and/or updated database with Add-Migration [name] and Update-Database

Most of my other problems are further explained in here: Controller Action not triggered - Simple Project - ASP.NET MVC CORE 2.0 - also check the comments to both this post and the linked post

If anybody has same problems, feel free to write me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM