问题
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.
For some reason, IActionResult RegisterUser
isn't triggered when submitting a form (I tried setting breakpoints, nothing happened). Can anyone detect why?
Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
var connection = @"Server=(localdb)\mssqllocaldb;Database=APIExercise2;Trusted_Connection=True;ConnectRetryCount=0";
services.AddDbContext<DataContext>(options => options.UseSqlServer(connection));
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<DataContext>();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc(routes =>
{
routes.MapRoute("Default", "{controller=Account}/{action=Index}");
});
app.UseFileServer();
}
}
Index.cshtml
@model CS_ConfigSettings.Models.Register
<form asp-controller="Account" asp-action="RegisterUser" method="post">
<input asp-for="Email" type="text" name="Email" id="Email" />
<input asp-for="Password" type="password" name="Password" id="Password" />
<button type="submit">Submit</button>
</form>
Controller
public class AccountController : Controller
{
private readonly UserManager<IdentityUser> _userManager;
public AccountController(UserManager<IdentityUser> userManager)
{
_userManager = userManager;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> RegisterUser(Register register)
{
var user = new IdentityUser
{
Email = register.Email
};
var result = await _userManager.CreateAsync(user, register.Password);
return View();
}
}
Register.cs
public class Register
{
public int Id { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
}
DataContext.cs
public class DataContext : DbContext
{
public DbSet<Register> register { get; set; }
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
Database.EnsureCreated();
}
}
When I submit the form, the breakpoints set in Controller-action RegisterUser
aren't triggered, and the Database-table register
isn't updated.
Thank you in advance.
回答1:
so you do realize that Identity creates tables for you? They are usually named AspNetUsers, AspNetRoles, AspNetRoleUsers, etc... so creating register
will be a table that Identity will never use.
If those tables listed previously aren't in your database created then you need to create a migration, usually your initial
migration which creates all of the Identity Tables. either using the PMC commands or command line with dotnet
. I suggest that you re-create the project with Individual users accounts selected to scaffold Identity features for you.
The fact that you haven't been able to hit that method with a break point... For one that UseFileServer is interfering with MVC... always always have UseMVC()
be the last entry. Order does matter.
As soon as that method does get hit it will error out since UserManager will die due the tables not existing since that will be location of the new created user in AspNetUsers
commandline: dotnet ef migrations add <nameofmigration>
PMC: Add-Migration <nameofmigration>
then run Update-Database
this will commit all the changes you just made.
https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/
Code Fragment from one of my projects
//remainder of Startup.cs left out for brevity
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseIdentityServer();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
来源:https://stackoverflow.com/questions/53264932/controller-action-not-triggered-simple-project-asp-net-mvc-core-2-0