如何将控制器连接到 Razor Pages 中的页面

How to connect a Controller to a Page in Razor Pages

我正在尝试将身份添加到我的网站,我有一个控制器,目前应该在他们点击我的注册表单上的注册按钮时将用户添加到数据库,其 URL 是(localhost :44369/Account/Register)。我的问题是我不认为它实际上在使用控制器。我认为这可能是路由或端点的问题,但我不确定。这是我的控制器:

namespace ThinBlueLie.Controllers
{
    public class AccountController : Controller
    {
        private readonly UserManager<IdentityUser> userManager;
        private readonly SignInManager<IdentityUser> signInManager;

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

        [HttpGet]
        public IActionResult Register()
        {            
            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Register(RegisterModel model)
        {
            var errors = ModelState.Values.SelectMany(v => v.Errors);
            if (ModelState.IsValid)
            {
                var user = new IdentityUser {UserName = model.Username, Email = model.Email};
                var result = await userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await signInManager.SignInAsync(user, isPersistent: false); //change isPersistent to true later
                    return RedirectToPage("./Index");
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }
            return View(model);
        }
    }
}

这是我的启动:

namespace ThinBlueLie
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {            
            services.AddDbContext<ThinbluelieContext>(options =>
            {
                options.UseMySql(Configuration.GetConnectionString("DefaultConnection"));
            });

            services.AddIdentity<IdentityUser, IdentityRole>()
                .AddEntityFrameworkStores<ThinbluelieContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();
            services.AddControllersWithViews();
            services.AddRazorPages()
                .AddRazorRuntimeCompilation();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();


            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            //app.UseMvc(routes =>
            //{
            //    routes.MapRoute("default", "controller=Home}/{action=Index}/{id?}");
            //});
            
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
                endpoints.MapRazorPages();
            });
        }
    }
}

这是我的页面:

@page
@model ThinBlueLie.Pages.RegisterModel

<div class="container-fluid h-100 row nogap">
    <div class="card border-secondary mx-auto center col-lg-3 col-md-4 p-0" style="margin-top:100px;">
        <div class="card-header">
            Register
            <a class="float-right" asp-page="/Login">Login</a>
        </div>
        <form asp-action="Register" asp-controller="Account" method="post">
            <div class="card-body text-secondary">
                <div asp-validation-summary="All" class="text-danger"></div>
                <div class="form-group">
                    <label asp-for="Email" class="control-label">Email</label>
                    <input asp-for="Email" class="form-control">
                    <span asp-validation-for="Email" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label  asp-for="Password"class="control-label"></label>
                    <input asp-for="Password" class="form-control" >
                    <span asp-validation-for="Password" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="ConfirmPassword" class="control-label"></label>
                    <input asp-for="ConfirmPassword" class="form-control">
                    <span asp-validation-for="ConfirmPassword" class="text-danger"></span>
                </div>                      
                <div class="form-group">
                    <label asp-for="Username" class="control-label"></label>
                    <input type="text" asp-for="Username" class="form-control">
                    <span asp-validation-for="Username" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <input type="submit" value="Register" class="btn btn-primary mb-1" style="float:right" />
                </div>
            </div>
        </form>
        <div class="card-footer">
            <a>Log in with Google</a>
        </div>
    </div>
</div>

@section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }

最后是我的模特:

namespace ThinBlueLie.Pages
{
    public class RegisterModel : PageModel
    {
        
        [Required]
        [EmailAddress]
        public string Email { get; set; }
        
        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Confirm Password")]
        [Compare("Password", ErrorMessage = "Passwords don't match.")]
        public string ConfirmPassword { get; set; }
        
        [Required]
        public string  Username { get; set; }
       
    }
}

Bubinga,它正在使用 endpoints 路由将您的 url 路径导航到控制器。

Routing 负责匹配传入的 HTTP 请求。 Net Core 3.1 使用端点路由将路由匹配和解析功能与端点调度功能分离。

综上所述,请求路径(/Account/Register)匹配AccountController/RegisterAction。 当 action 被执行时,它将最终重定向到 View(如果不重新分配则与您的操作同名)和 Model

您可以从 here 那里学习路由的基础知识

您可以从 here.

学习 MVC 的路由