Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将控制器连接到Razor页面中的页面_C#_Asp.net Mvc_Asp.net Core_Asp.net Identity_Razor Pages - Fatal编程技术网

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

C# 如何将控制器连接到Razor页面中的页面,c#,asp.net-mvc,asp.net-core,asp.net-identity,razor-pages,C#,Asp.net Mvc,Asp.net Core,Asp.net Identity,Razor Pages,我正在尝试向我的网站添加标识,我有一个控制器,当用户点击我的注册表单上的注册按钮时,该控制器当前应该向数据库中添加一个用户,其URL为(localhost:44369/Account/register)。我的问题是,我不认为它实际上在使用控制器。我认为这可能是路由或端点的问题,但我不确定。这是我的控制器: namespace ThinBlueLie.Controllers { public class AccountController : Controller {

我正在尝试向我的网站添加标识,我有一个控制器,当用户点击我的注册表单上的注册按钮时,该控制器当前应该向数据库中添加一个用户,其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);
        }
    }
}

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

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

总之,请求路径(
/Account/Register
)与
AccountController/RegisterAction
匹配。 执行
操作
后,它最终将重定向到
视图
(如果未重新分配,则与您的操作同名)

您可以从中学习布线的基本原理


您可以从中学习MVC的路由。

谢谢您的详细回答。最后,我在相应的操作中添加了一个[Route(“Account/Register”)]来修复它。这给了我一个错误,我抱怨抽象类,所以我删除了“:PageModel”,它工作了。
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; }
       
    }
}