随着技术的进步,跨平台开发已经成为了标配,在此大背景下,ASP.NET Core也应运而生。本文主要利用ASP.NET Core开发一个学生管理系统为例,简述ASP.NET Core开发的常见知识点,仅供学习分享使用,如有不足之处,还请指正。
开发学生管理系统,涉及知识点,如下所示:
文件-->新建-->项目-->ASP.NET Core Web应用(模型-视图-控制器),如下所示:
然后点击下一步,进入配置新项目页面,输入项目名称【SMS=Student Management System】及保存位置,然后点击下一步,如下所示:
选择其他信息【目标框架选择.NET 5.0】,然后点击创建,如下所示:
通过默认创建的项目,如下所示:
在Controllers文件夹-->右键添加-->控制器,如下所示:
打开创建视图控制器窗口,选择MVC控制器-空,然后点击添加。 如下所示:
弹出添加新项窗口,选择MVC控制器-空,输入控制器名称,点击创建即可,如下所示:
控制器代码如下所示:
1 namespace SMS.Controllers 2 { 3 public class LoginController : Controller 4 { 5 private DataContext dataContext; 6 7 public LoginController(DataContext context) { 8 dataContext = context; 9 } 10 11 [HttpGet] 12 public IActionResult Index() 13 { 14 return View(); 15 } 16 17 [HttpPost] 18 public IActionResult Login(User user) 19 { 20 if (string.IsNullOrEmpty(user.UserName) || string.IsNullOrEmpty(user.Password)) 21 { 22 ViewBag.Msg = "用户名或密码为空"; 23 return View("Index", user); 24 } 25 else { 26 var item = dataContext.Users.FirstOrDefault(i=>i.UserName==user.UserName && i.Password == user.Password); 27 if (item != null) 28 { 29 HttpContext.Session.SetInt32("UserId",item.Id); 30 return Redirect("/Home"); 31 } 32 else 33 { 34 ViewBag.Msg = "用户名或密码验证错误"; 35 return View("Index", user); 36 } 37 38 } 39 } 40 } 41 }
在Views文件夹下新增Login文件夹,然后新增视图【Index.cshtml】,如下所示:
然后选择空视图,如下所示:
输入视图名称【Index.cshtml】,点击添加即可,如下所示:
登录页面,添加如下代码,如下所示:
1 @{ Layout = null;} 2 <!DOCTYPE html> 3 <html> 4 <head> 5 <title>学生管理系统</title> 6 <link rel="stylesheet" href="/css/login.css"> 7 <!-- For-Mobile-Apps-and-Meta-Tags --> 8 <meta name="viewport" content="width=device-width, initial-scale=1" /> 9 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 10 11 <!-- //For-Mobile-Apps-and-Meta-Tags --> 12 13 </head> 14 15 <body> 16 <h1>学生管理系统</h1> 17 <div class="container w3"> 18 19 <form action="/Login/Login" method="post"> 20 <div class="username"> 21 <span class="username">Username:</span> 22 <input type="text" id="UserName" name="UserName" class="name" placeholder="" required=""> 23 <div class="clear"></div> 24 </div> 25 <div class="password-agileits"> 26 <span class="username">Password:</span> 27 <input type="password" id="Password" name="Password" class="password" placeholder="" required=""> 28 <div class="clear"></div> 29 </div> 30 <div class="rem-for-agile"> 31 <input type="checkbox" name="remember" class="remember">记住密码<br> 32 </div> 33 <div class="login-w3"> 34 <input type="submit" class="login" value="登 录"> 35 </div> 36 <div class="clear"></div> 37 <div style="color:red;font-size:13px;"> 38 @ViewBag.Msg 39 </div> 40 </form> 41 </div> 42 <div class="footer-w3l"> 43 <p> © 2021 学生管理系统. All Rights Reserved | Design by 小六公子</p> 44 </div> 45 </body> 46 </html>
在Models文件夹下,右键添加类,如下所示:
输入模型名称【User】,点击添加即可,如下所示:
用户模型User,如下所示:
1 namespace SMS.Models 2 { 3 public class User 4 { 5 /// <summary> 6 /// 用户唯一标识 7 /// </summary> 8 public int Id { get; set; } 9 10 /// <summary> 11 /// 登录账号 12 /// </summary> 13 public string UserName { get; set; } 14 15 /// <summary> 16 /// 密码 17 /// </summary> 18 public string Password { get; set; } 19 20 /// <summary> 21 /// 显示名称 22 /// </summary> 23 public string NickName { get; set; } 24 } 25 }
数据库操作采用EntityFrameCore框架,继承自DbContext,如下所示:
1 namespace SMS.Models 2 { 3 public class DataContext:DbContext 4 { 5 public DbSet<User> Users { get; set; } 6 7 public DataContext(DbContextOptions options) : base(options) 8 { 9 10 } 11 } 12 }
创建数据库和表并构造数据,如下所示:
连接数据库,需要在配置文件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的注入,如下所示:
1 namespace SMS 2 { 3 public class Startup 4 { 5 public Startup(IConfiguration configuration) 6 { 7 Configuration = configuration; 8 } 9 10 public IConfiguration Configuration { get; } 11 12 // This method gets called by the runtime. Use this method to add services to the container. 13 public void ConfigureServices(IServiceCollection services) 14 { 15 services.AddControllersWithViews(); 16 //数据库EntityFrameworkCore注入 17 services.AddDbContext<DataContext>(options=>options.UseSqlServer(Configuration.GetConnectionString("Default"))); 18 services.AddHttpContextAccessor(); 19 services.AddSession();//配置session访问服务 20 } 21 22 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 23 public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 24 { 25 if (env.IsDevelopment()) 26 { 27 app.UseDeveloperExceptionPage(); 28 } 29 else 30 { 31 app.UseExceptionHandler("/Home/Error"); 32 // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. 33 app.UseHsts(); 34 } 35 app.UseHttpsRedirection(); 36 app.UseStaticFiles(); 37 38 app.UseRouting(); 39 app.UseSession();//需是注入session 40 app.UseAuthorization(); 41 42 app.UseEndpoints(endpoints => 43 { 44 endpoints.MapControllerRoute( 45 name: "default", 46 pattern: "{controller=Home}/{action=Index}/{id?}"); 47 }); 48 } 49 } 50 }
经过以上步骤,登录功能已经做好,运行程序。然后数据账号密码,点击登录进行跳转,如下所示:
以上就是学生管理系统的登录功能实现,后续功能再继续介绍。旨在抛砖引玉,一起学习,共同进步。
浙江小矶春日【作者】范成大 【朝代】宋
客里无人共一杯,故园桃李为谁开? 春潮不管天涯恨,更卷西兴暮雨来。