随着技术的进步,跨平台开发已经成为了标配,在此大背景下,ASP.NET Core也应运而生。本文主要利用ASP.NET Core开发一个学生管理系统为例,简述ASP.NET Core开发的常见知识点,仅供学习分享使用,如有不足之处,还请指正。
开发学生管理系统,涉及知识点,如下所示:
文件-->新建-->项目-->ASP.NET Core Web应用(模型-视图-控制器),如下所示:
然后点击下一步,进入配置新项目页面,输入项目名称【SMS=Student Management System】及保存位置,然后点击下一步,如下所示:
选择其他信息【目标框架选择.NET 5.0】,然后点击创建,如下所示:
通过默认创建的项目,如下所示:
在Controllers文件夹-->右键添加-->控制器,如下所示:
打开创建视图控制器窗口,选择MVC控制器-空,然后点击添加。 如下所示:
弹出添加新项窗口,选择MVC控制器-空,输入控制器名称,点击创建即可,如下所示:
控制器代码如下所示:
namespace SMS.Controllers { public class LoginController : Controller { private DataContext dataContext; public LoginController(DataContext context) { dataContext = context; } [HttpGet] public IActionResult Index() { return View(); } [HttpPost] public IActionResult Login(User user) { if (string.IsNullOrEmpty(user.UserName) || string.IsNullOrEmpty(user.Password)) { ViewBag.Msg = "用户名或密码为空"; return View("Index", user); } else { var item = dataContext.Users.FirstOrDefault(i=>i.UserName==user.UserName && i.Password == user.Password); if (item != null) { HttpContext.Session.SetInt32("UserId",item.Id); return Redirect("/Home"); } else { ViewBag.Msg = "用户名或密码验证错误"; return View("Index", user); } } } } }
在Views文件夹下新增Login文件夹,然后新增视图【Index.cshtml】,如下所示:
然后选择空视图,如下所示:
输入视图名称【Index.cshtml】,点击添加即可,如下所示:
登录页面,添加如下代码,如下所示:
@{ Layout = null;} <!DOCTYPE html> <html> <head> <title>学生管理系统</title> <link rel="stylesheet" href="/css/login.css"> <!-- For-Mobile-Apps-and-Meta-Tags --> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- //For-Mobile-Apps-and-Meta-Tags --> </head> <body> <h1>学生管理系统</h1> <div class="container w3"> <form action="/Login/Login" method="post"> <div class="username"> <span class="username">Username:</span> <input type="text" id="UserName" name="UserName" class="name" placeholder="" required=""> <div class="clear"></div> </div> <div class="password-agileits"> <span class="username">Password:</span> <input type="password" id="Password" name="Password" class="password" placeholder="" required=""> <div class="clear"></div> </div> <div class="rem-for-agile"> <input type="checkbox" name="remember" class="remember">记住密码<br> </div> <div class="login-w3"> <input type="submit" class="login" value="登 录"> </div> <div class="clear"></div> <div style="color:red;font-size:13px;"> @ViewBag.Msg </div> </form> </div> <div class="footer-w3l"> <p> © 2021 学生管理系统. All Rights Reserved | Design by 小六公子</p> </div> </body> </html>
在Models文件夹下,右键添加类,如下所示:
输入模型名称【User】,点击添加即可,如下所示:
用户模型User,如下所示:
namespace SMS.Models { public class User { /// <summary> /// 用户唯一标识 /// </summary> public int Id { get; set; } /// <summary> /// 登录账号 /// </summary> public string UserName { get; set; } /// <summary> /// 密码 /// </summary> public string Password { get; set; } /// <summary> /// 显示名称 /// </summary> public string NickName { get; set; } } }
数据库操作采用EntityFrameCore框架,继承自DbContext,如下所示:
namespace SMS.Models { public class DataContext:DbContext { public DbSet<User> Users { get; set; } public DataContext(DbContextOptions options) : base(options) { } } }
创建数据库和表并构造数据,如下所示:
连接数据库,需要在配置文件appsettings.json中,添加数据库连接字符串,如下所示:
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "ConnectionStrings": { "Default": "Server=localhost;Database=SMS;Trusted_Connection=True;User Id=sa;Password=abc123" }, "AllowedHosts": "*" }
在Startup.cs中,添加EntittyFramework的注入,如下所示:
namespace SMS { 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.AddControllersWithViews(); //数据库EntityFrameworkCore注入 services.AddDbContext<DataContext>(options=>options.UseSqlServer(Configuration.GetConnectionString("Default"))); services.AddHttpContextAccessor(); services.AddSession();//配置session访问服务 } // 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(); } else { app.UseExceptionHandler("/Home/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.UseSession();//需是注入session app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
经过以上步骤,登录功能已经做好,运行程序。然后数据账号密码,点击登录进行跳转,如下所示:
以上就是学生管理系统的登录功能实现,后续功能再继续介绍。旨在抛砖引玉,一起学习,共同进步。