导读:本期聚焦于小伙伴创作的《C#如何实现用户登录功能?6种常用实现方式详解》,敬请观看详情,探索知识的价值。以下视频、文章将为您系统阐述其核心内容与价值。如果您觉得《C#如何实现用户登录功能?6种常用实现方式详解》有用,将其分享出去将是对创作者最好的鼓励。

用户登录是绝大多数应用系统的基础功能,C#作为常用的应用开发语言,在不同类型的项目中实现登录功能的方式存在差异,开发者可以根据项目类型选择合适的实现方案。

C#如何实现用户登录功能?6种常用实现方式详解

C#实现用户登录功能的6种常用方式

1. WinForms+本地文件存储登录

这种方式适合小型本地桌面工具,用户信息存储在本地文本文件或XML文件中,实现简单无需数据库依赖。

核心实现逻辑是读取本地存储的用户名密码,和用户输入的信息做比对,示例代码如下:

using System;
using System.IO;
using System.Windows.Forms;

namespace WinFormsLoginDemo
{
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            string inputUser = txtUser.Text.Trim();
            string inputPwd = txtPwd.Text.Trim();
            // 本地用户信息文件路径,格式为 用户名,密码 每行一条
            string userFilePath = "users.txt";
            if (!File.Exists(userFilePath))
            {
                MessageBox.Show("用户数据文件不存在");
                return;
            }
            string[] userLines = File.ReadAllLines(userFilePath);
            bool loginSuccess = false;
            foreach (string line in userLines)
            {
                if (string.IsNullOrEmpty(line)) continue;
                string[] userInfo = line.Split(',');
                if (userInfo.Length != 2) continue;
                if (userInfo[0] == inputUser && userInfo[1] == inputPwd)
                {
                    loginSuccess = true;
                    break;
                }
            }
            if (loginSuccess)
            {
                MessageBox.Show("登录成功");
                // 跳转到主界面逻辑
            }
            else
            {
                MessageBox.Show("用户名或密码错误");
            }
        }
    }
}

2. WinForms+SQLite数据库登录

适合需要本地存储多用户数据、且不想依赖外部数据库的桌面应用,使用轻量级的SQLite数据库存储用户信息。

首先需要引入System.Data.SQLite库,核心查询逻辑如下:

using System;
using System.Data;
using System.Data.SQLite;
using System.Windows.Forms;

namespace WinFormsSQLiteLogin
{
    public partial class LoginForm : Form
    {
        // SQLite数据库连接字符串,本地db文件
        private string connStr = "Data Source=local_users.db;Version=3;";

        private void btnLogin_Click(object sender, EventArgs e)
        {
            string inputUser = txtUser.Text.Trim();
            string inputPwd = txtPwd.Text.Trim();
            using (SQLiteConnection conn = new SQLiteConnection(connStr))
            {
                conn.Open();
                string sql = "SELECT COUNT(1) FROM users WHERE username=@user AND password=@pwd";
                using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
                {
                    cmd.Parameters.AddWithValue("@user", inputUser);
                    cmd.Parameters.AddWithValue("@pwd", inputPwd);
                    int count = Convert.ToInt32(cmd.ExecuteScalar());
                    if (count > 0)
                    {
                        MessageBox.Show("登录成功");
                    }
                    else
                    {
                        MessageBox.Show("用户名或密码错误");
                    }
                }
            }
        }
    }
}

3. WinForms+SQL Server数据库登录

适合企业级桌面应用,用户信息存储在远程或本地的SQL Server数据库中,支持多客户端同时访问。

核心实现使用ADO.NET操作SQL Server,示例代码如下:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WinFormsSqlServerLogin
{
    public partial class LoginForm : Form
    {
        // SQL Server连接字符串,根据实际环境修改
        private string connStr = "Server=127.0.0.1;Database=UserDB;User Id=sa;Password=123456;";

        private void btnLogin_Click(object sender, EventArgs e)
        {
            string inputUser = txtUser.Text.Trim();
            string inputPwd = txtPwd.Text.Trim();
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                string sql = "SELECT user_id FROM sys_users WHERE user_name=@user AND user_pwd=@pwd AND is_delete=0";
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddWithValue("@user", inputUser);
                    cmd.Parameters.AddWithValue("@pwd", inputPwd);
                    object result = cmd.ExecuteScalar();
                    if (result != null)
                    {
                        MessageBox.Show("登录成功,用户ID:" + result.ToString());
                    }
                    else
                    {
                        MessageBox.Show("用户名或密码错误");
                    }
                }
            }
        }
    }
}

4. ASP.NET Web Forms表单登录

适合传统的ASP.NET Web应用,使用Web Forms的表单认证机制实现登录状态保持。

首先在Web.config中配置表单认证:

<configuration>
  <system.web>
    <authentication mode="Forms">
      <forms loginUrl="Login.aspx" defaultUrl="Default.aspx" timeout="30" />
    </authentication>
    <authorization>
      <deny users="?" />
    </authorization>
  </system.web>
</configuration>

登录页面后台处理逻辑:

using System;
using System.Web.Security;
using System.Data.SqlClient;

namespace WebFormsLogin
{
    public partial class Login : System.Web.UI.Page
    {
        private string connStr = "Server=127.0.0.1;Database=UserDB;User Id=sa;Password=123456;";

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            string inputUser = txtUser.Text.Trim();
            string inputPwd = txtPwd.Text.Trim();
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                string sql = "SELECT user_name FROM sys_users WHERE user_name=@user AND user_pwd=@pwd";
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddWithValue("@user", inputUser);
                    cmd.Parameters.AddWithValue("@pwd", inputPwd);
                    object userName = cmd.ExecuteScalar();
                    if (userName != null)
                    {
                        // 创建表单认证票据,保持登录状态
                        FormsAuthentication.SetAuthCookie(userName.ToString(), chkRemember.Checked);
                        Response.Redirect("Default.aspx");
                    }
                    else
                    {
                        lblMsg.Text = "用户名或密码错误";
                    }
                }
            }
        }
    }
}

5. ASP.NET MVC+Identity登录

适合基于ASP.NET MVC架构的Web应用,使用微软官方的Identity身份认证框架,自带用户管理、密码哈希、角色管理等功能。

首先在NuGet安装Microsoft.AspNet.Identity.Core、Microsoft.AspNet.Identity.EntityFramework包,登录控制器代码如下:

using System.Threading.Tasks;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using WebMvcLogin.Models;

namespace WebMvcLogin.Controllers
{
    public class AccountController : Controller
    {
        private UserManager<ApplicationUser> _userManager;

        public AccountController()
        {
            var context = new ApplicationDbContext();
            var store = new UserStore<ApplicationUser>(context);
            _userManager = new UserManager<ApplicationUser>(store);
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<ActionResult> Login(LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var user = await _userManager.FindAsync(model.UserName, model.Password);
            if (user != null)
            {
                var identity = await _userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
                // 登录并写入Cookie
                System.Web.HttpContext.Current.GetOwinContext().Authentication.SignIn(identity);
                return RedirectToAction("Index", "Home");
            }
            ModelState.AddModelError("", "用户名或密码错误");
            return View(model);
        }
    }
}

6. ASP.NET Core JWT令牌登录

适合前后端分离的Web应用、Web API项目,使用JWT(JSON Web Token)实现无状态的登录认证,前端请求接口时携带令牌即可完成身份校验。

首先在appsettings.json配置JWT参数:

{
  "Jwt": {
    "Key": "ThisIsASecureKeyForJwtDemo123456",
    "Issuer": "ipipp.com",
    "Audience": "ipipp.com",
    "ExpireMinutes": 30
  }
}

登录接口生成令牌的代码如下:

using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using WebApiLogin.Models;

namespace WebApiLogin.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        private readonly IConfiguration _configuration;

        public AuthController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [HttpPost("login")]
        public IActionResult Login([FromBody] LoginDto loginDto)
        {
            // 此处省略数据库校验用户名密码的逻辑,假设校验通过
            if (loginDto.UserName == "admin" && loginDto.Password == "123456")
            {
                var claims = new[]
                {
                    new Claim(ClaimTypes.Name, loginDto.UserName),
                    new Claim(ClaimTypes.Role, "Admin")
                };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                var token = new JwtSecurityToken(
                    issuer: _configuration["Jwt:Issuer"],
                    audience: _configuration["Jwt:Audience"],
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(Convert.ToDouble(_configuration["Jwt:ExpireMinutes"])),
                    signingCredentials: creds);
                return Ok(new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(token)
                });
            }
            return BadRequest("用户名或密码错误");
        }
    }
}

不同登录方式的适用场景对比

开发者可以根据项目类型选择合适的登录实现方式,具体对比如下:

登录方式适用场景优点缺点
WinForms+本地文件存储小型本地工具、单机应用实现简单,无外部依赖安全性低,不支持多用户并发
WinForms+SQLite本地多用户桌面应用轻量,无需独立数据库服务不适合多客户端远程访问
WinForms+SQL Server企业级桌面应用支持多客户端,数据管理方便需要部署SQL Server服务
ASP.NET Web Forms表单登录传统ASP.NET Web应用自带认证机制,开发快架构较老,不适合新项目
ASP.NET MVC+IdentityASP.NET MVC架构Web应用功能完善,自带用户管理耦合度较高
ASP.NET Core JWT登录前后端分离、Web API项目无状态,适合分布式部署需要实现令牌刷新逻辑

登录功能开发注意事项

  • 密码存储不要明文保存,建议使用哈希算法(如SHA256、BCrypt)加密后存储,验证时比对哈希值。
  • 登录接口需要添加防暴力破解机制,比如限制同一IP短时间内的登录尝试次数。
  • 生产环境的所有接口通信建议使用HTTPS协议,避免登录信息被窃听。
  • 登录状态保持的过期时间需要根据业务场景合理设置,避免过长带来安全风险。

C#用户登录WinFormsASP.NETADO.NET修改时间:2026-06-21 20:45:52

免责声明:​ 已尽一切努力确保本网站所含信息的准确性。网站内容多为原创整理与精心编撰,观点力求客观中立。本站旨在免费分享,内容仅供个人学习、研究或参考使用。若引用了第三方作品,版权归原作者所有。如内容涉及您的权益,请联系我们处理。
内容垂直聚焦
专注技术核心技术栏目,确保每篇文章深度聚焦于实用技能。从代码技巧到架构设计,为用户提供无干扰的纯技术知识沉淀,精准满足专业提升需求。
知识结构清晰
覆盖从开发到部署的全链路。AI、前端、编程、数据库、服务器、建站、系统层层递进,构建清晰学习路径,帮助用户系统化掌握开发与运维所需的核心技术。
深度技术解析
拒绝泛泛而谈,深入技术细节与实践难点。无论是数据库优化还是服务器配置,均结合真实场景与代码示例进行剖析,致力于提供可直接应用于工作的解决方案。
专业领域覆盖
精准对应开发生命周期。从前端界面到后端编程,从数据库操作到服务器运维,形成完整闭环,一站式满足全栈工程师和运维人员的技术需求。
即学即用高效
内容强调实操性,步骤清晰、代码完整。用户可根据教程直接复现和应用于自身项目,显著缩短从学习到实践的距离,快速解决开发中的具体问题。
持续更新保障
专注既定技术方向进行长期、稳定的内容输出。确保各栏目技术文章持续更新迭代,紧跟主流技术发展趋势,为用户提供经久不衰的学习价值。