未触发控制器操作-简单项目-ASP.NET MVC CORE 2.0 [英] Controller Action not triggered - Simple Project - ASP.NET MVC CORE 2.0

查看:71
本文介绍了未触发控制器操作-简单项目-ASP.NET MVC CORE 2.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的Web应用程序,试图让人们注册用户.因此,我尝试将用户注册数据保存到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.

由于某种原因,提交表单时未触发IActionResult RegisterUser(我尝试设置断点,没有任何反应).谁能找到原因?

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>

控制器

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();
    }
}

提交表单时,不会触发在控制器操作RegisterUser中设置的断点,并且不会更新数据库表register.

When I submit the form, the breakpoints set in Controller-action RegisterUser aren't triggered, and the Database-table register isn't updated.

谢谢.

推荐答案

,您是否意识到Identity为您创建了表?它们通常被命名为AspNetUsers,AspNetRoles,AspNetRoleUsers等,因此创建register将是Identity永远不会使用的表.

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.

如果先前列出的那些表不在您的数据库中创建,则您需要创建一个迁移,通常是initial迁移,它会创建所有身份表.使用PMC命令或带有dotnet的命令行.我建议您使用选择的个人用户帐户重新创建项目,以为您提供身份"功能.

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.

您无法使用断点来执行该方法的事实...对于UseFileServer干扰MVC的情况...始终总是将UseMVC()作为最后一个条目.顺序很重要.

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.

一旦该方法被击中,它将出错,因为UserManager将由于表不存在而死亡,因为这将是新创建的用户在AspNetUsers

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

命令行:dotnet ef migrations add <nameofmigration>

PMC:Add-Migration <nameofmigration>

然后运行Update-Database,这将提交您刚刚进行的所有更改.

then run Update-Database this will commit all the changes you just made.

https://docs.microsoft.com/zh-cn/ef/core/managing-schemas/migrations/

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

            
        });

这篇关于未触发控制器操作-简单项目-ASP.NET MVC CORE 2.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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