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

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+Identity | ASP.NET MVC架构Web应用 | 功能完善,自带用户管理 | 耦合度较高 |
| ASP.NET Core JWT登录 | 前后端分离、Web API项目 | 无状态,适合分布式部署 | 需要实现令牌刷新逻辑 |
登录功能开发注意事项
- 密码存储不要明文保存,建议使用哈希算法(如SHA256、BCrypt)加密后存储,验证时比对哈希值。
- 登录接口需要添加防暴力破解机制,比如限制同一IP短时间内的登录尝试次数。
- 生产环境的所有接口通信建议使用HTTPS协议,避免登录信息被窃听。
- 登录状态保持的过期时间需要根据业务场景合理设置,避免过长带来安全风险。