简体   繁体   English

带有 ASP.NET 内核 (MVC) 的登录页面

[英]Login Page with ASP.NET Core (MVC)

I am trying to learn asp.net core (MVC), and I am posting this question after trying to implement everything that I could understand from Google.我正在尝试学习 asp.net 核心(MVC),并且在尝试实现我可以从 Google 理解的所有内容后发布这个问题。

I want to create a simple login Page.我想创建一个简单的登录页面。 I have earlier worked on asp.net framework with ado.net and webforms using edmx, but I learned that edmx and webforms are now outdated.我之前曾在 asp.net 框架和 ado.net 和使用 edmx 的 webforms 上工作,但我了解到 edmx 和 webforms 现在已经过时了。 So, I wanted to learn the new method.所以,我想学习新方法。

These are the tables and stored procedure I created这些是我创建的表和存储过程

create table users(userId int identity(1,1) primary key, username varchar(20), password varchar(20)) create proc login( @username varchar(20), @password varchar(20) ) as begin if exists(select * from users where username = @username and password=@password) select 'Success' as UserExists else select 'Failed' as UserExists end

Then I created the Model Class -然后我创建了 Model Class -

 public class Login { [Key] public int userId { get; set; } [Required(ErrorMessage = "Username is requried;")] public string username { get; set; } [Required(ErrorMessage = "Password is requried;")] public string password { get set } }

Then I added model in my project.然后我在我的项目中添加了 model。 I referred this link我提到了这个链接

https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-6.0&tabs=visual-studio https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-6.0&tabs=visual-studio

Then referencing the following link, I added my connection string details in appstring.json file -然后参考以下链接,我在 appstring.json 文件中添加了我的连接 string 详细信息 -

link https://www.c-sharpcorner.com/article/crud-operations-in-asp-net-core-mvc-net-5-0/链接https://www.c-sharpcorner.com/article/crud-operations-in-asp-net-core-mvc-net-5-0/

 "WebsiteContext": "Server=DELL\\SQLEXPRESS01;Database=website;Trusted_Connection=True;MultipleActiveResultSets=true"

This is startup.cs这是startup.cs

 public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddDbContext<WebsiteContext>(options => options.UseSqlServer(Configuration.GetConnectionString("WebsiteContext"))); }

I created the login.cshtml with basic asp.net.我用基本的 asp.net 创建了 login.cshtml。

 @{ ViewData["Title"] = "Login"; } <h1>Login</h1> <div> <table> <tr> <td> <asp:TextBox ID="username"></asp:TextBox> </td> <td> <asp:TextBox ID="password"></asp:TextBox> </td> </tr> <tr> <td> <asp:Button ID="submit"></asp:Button> </td> </tr> </table> </div>

Now, I am confused as how should I proceed next.现在,我很困惑下一步应该如何进行。 Here is my LoginController class.这是我的登录控制器 class。 This was generated automatically after scaffolding.这是在搭建脚手架后自动生成的。

 public class LoginController: Controller { private readonly WebsiteContext _context; public LoginController(WebsiteContext context) { _context = context; } // GET: Login public async Task<IActionResult> Index() { return View(await _context.Login.ToListAsync()); } // GET: Login/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var login = await _context.Login.FirstOrDefaultAsync(m => m.userId == id); if (login == null) { return NotFound(); } return View(login); } // GET: Login/Create public IActionResult Create() { return View(); } // POST: Login/Create // To protect from overposting attacks, enable the specific properties you want to bind to, for // more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("userId,username,password")] Login login) { if (ModelState.IsValid) { _context.Add(login); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(login); } }

I know the process of ado.net but now I am confused how should I proceed with mvc.我知道 ado.net 的过程,但现在我很困惑如何继续使用 mvc。

Please guide me.请指导我。 Thank you谢谢

If you just do a simple login test, you need to add the verification that the username and password are consistent with the database in the controller.如果只是做一个简单的登录测试,需要在controller中添加用户名密码与数据库一致的验证。 You can refer to the following code:可以参考以下代码:

Controller: Controller:

 public IActionResult Login() { return View(); } [HttpPost] public async Task<IActionResult> Login(Login model) { if (ModelState.IsValid) { var User = from m in _context.Login select m; User = User.Where(s => s.username.Contains(model.username)); if (User.Count().= 0) { if (User.First().password == model;password) { return RedirectToAction("Success"); } } } return RedirectToAction("Fail"); } public IActionResult Success() { return View(); } public IActionResult Fail() { return View() }

login.cshtml:登录.cshtml:

 @model _2022070401.Models.Login <h1>Login</h1> <hr /> <div class="row"> <div class="col-md-4"> <form asp-action="Login" asp-controller="Login"> <div asp-validation-summary="All" class="text-danger"></div> <div class="form-group"> <label asp-for="username" class="control-label"></label> <input asp-for="username" class="form-control" placeholder="Name" /> <span asp-validation-for="username" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="password" class="control-label"></label> <input asp-for="password" class="form-control" placeholder="Password" /> <span asp-validation-for="password" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Login" class="btn btn-primary" /> </div> </form> </div> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }

Test Result:测试结果:

在此处输入图像描述

Success:成功:

在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

Fail:失败:

在此处输入图像描述 在此处输入图像描述

If you have a business need for this, I recommend using Identity.如果您对此有业务需求,我建议您使用 Identity。 You can refer to this link and this one .你可以参考这个链接这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM