问题描述: 我在ASP.NET Core MVC中创建了一个注册/登录页面,但是在运行时遇到了问题。页面加载正常,但是当我尝试注册或登录时,什么都不发生。
解决方法:
示例代码:
// 注册页面的HTTP GET方法
[HttpGet]
public IActionResult Register()
{
return View();
}
// 注册页面的HTTP POST方法
[HttpPost]
public IActionResult Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
// 执行注册逻辑,保存用户信息等
// 重定向到其他页面或返回注册成功消息
}
return View(model);
}
// 登录页面的HTTP GET方法
[HttpGet]
public IActionResult Login()
{
return View();
}
// 登录页面的HTTP POST方法
[HttpPost]
public IActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
// 执行登录逻辑,验证用户信息等
// 重定向到其他页面或返回登录成功消息
}
return View(model);
}
@using (Html.BeginForm("Register", "Account", FormMethod.Post))来创建一个POST表单,其中"Register"是控制器中处理注册请求的方法名称,"Account"是控制器的名称。示例代码:
@model RegisterViewModel
@using (Html.BeginForm("Register", "Account", FormMethod.Post))
{
}
示例代码:
public class RegisterViewModel
{
[Required(ErrorMessage = "Username is required")]
public string Username { get; set; }
[Required(ErrorMessage = "Password is required")]
[DataType(DataType.Password)]
public string Password { get; set; }
// 其他字段和验证规则
}
示例代码:
@model RegisterViewModel
@model LoginViewModel
Startup.cs文件中正确地配置了身份验证和授权中间件。例如,你应该在ConfigureServices方法中添加身份验证服务,并在Configure方法中启用身份验证和授权中间件。示例代码:
public void ConfigureServices(IServiceCollection services)
{
// 添加身份验证服务
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(options =>
{
options.LoginPath = "/Account/Login"; // 登录页面的路径
});
// 其他服务配置
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// 启用身份验证和授权中间件
app.UseAuthentication();
// 其他中间件配置
}
希望以上解决方法能够帮助你解决ASP.NET