欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#利用ASP.NET Core开发学生管理系统详解

程序员文章站 2022-06-15 13:18:17
目录涉及知识点创建项目登录模块1. 创建控制器--logincontroller2. 创建登录视图3. 创建用户模型4. 创建数据库操作datacontext5. 创建数据库和表并构造数据6. 添加数...

随着技术的进步,跨平台开发已经成为了标配,在此大背景下,asp.net core也应运而生。本文主要利用asp.net core开发一个学生管理系统为例,简述asp.net core开发的常见知识点,仅供学习分享使用,如有不足之处,还请指正。

涉及知识点

开发学生管理系统,涉及知识点,如下所示:

开发工具:visual studio 2019

目标框架:.net 5.0

架构:mvc三层架构【model-view-controller】

创建项目

文件-->新建-->项目-->asp.net core web应用(模型-视图-控制器),如下所示:

C#利用ASP.NET Core开发学生管理系统详解

然后点击下一步,进入配置新项目页面,输入项目名称【sms=student management system】及保存位置,然后点击下一步,如下所示:

C#利用ASP.NET Core开发学生管理系统详解

选择其他信息【目标框架选择.net 5.0】,然后点击创建,如下所示:

C#利用ASP.NET Core开发学生管理系统详解

通过默认创建的项目,如下所示:

C#利用ASP.NET Core开发学生管理系统详解

登录模块

1. 创建控制器--logincontroller

在controllers文件夹-->右键添加-->控制器,如下所示:

C#利用ASP.NET Core开发学生管理系统详解

打开创建视图控制器窗口,选择mvc控制器-空,然后点击添加。 如下所示:

C#利用ASP.NET Core开发学生管理系统详解

弹出添加新项窗口,选择mvc控制器-空,输入控制器名称,点击创建即可,如下所示:

C#利用ASP.NET Core开发学生管理系统详解

控制器代码如下所示:

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);
                }

            }
        }
    }
}

2. 创建登录视图

在views文件夹下新增login文件夹,然后新增视图【index.cshtml】,如下所示:

C#利用ASP.NET Core开发学生管理系统详解

然后选择空视图,如下所示:

C#利用ASP.NET Core开发学生管理系统详解

输入视图名称【index.cshtml】,点击添加即可,如下所示:

C#利用ASP.NET Core开发学生管理系统详解

登录页面,添加如下代码,如下所示:

<!doctype html>
<html>
<head>
    <title>学生管理系统</title>
    <link rel="stylesheet" href="/css/login.css" rel="external nofollow" >
    <!-- 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>

3. 创建用户模型

在models文件夹下,右键添加类,如下所示:

C#利用ASP.NET Core开发学生管理系统详解

输入模型名称【user】,点击添加即可,如下所示:

C#利用ASP.NET Core开发学生管理系统详解

用户模型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; }
    }
}

4. 创建数据库操作datacontext

数据库操作采用entityframecore框架,继承自dbcontext,如下所示:

namespace sms.models
{
    public class datacontext:dbcontext
    {
        public dbset<user> users { get; set; }

        public datacontext(dbcontextoptions options) : base(options)
        {

        }
    }
}

5. 创建数据库和表并构造数据

创建数据库和表并构造数据,如下所示:

C#利用ASP.NET Core开发学生管理系统详解

6. 添加数据库连接配置

连接数据库,需要在配置文件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": "*"
}

7. 添加注入信息

在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?}");
            });
        }
    }
}

8. 运行测试

经过以上步骤,登录功能已经做好,运行程序。然后数据账号密码,点击登录进行跳转,如下所示:

C#利用ASP.NET Core开发学生管理系统详解

以上就是c#利用asp.net core开发学生管理系统详解的详细内容,更多关于c# asp.net core学生管理系统的资料请关注其它相关文章!