在.NET MVC项目中,Forms验证是ASP.NET提供的经典身份认证方案,它基于Cookie存储用户票据,能够轻松实现登录状态保持与页面访问限制。下面通过一个完整实例说明如何配置并使用它。

一、配置Web.config开启Forms验证
首先需要在项目的Web.config文件中配置认证模式为Forms,并设置登录页与超时时间。
<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="30" slidingExpiration="true" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>
上述配置表示未登录用户(?)禁止访问,会跳转到Account控制器的Login动作。
二、创建登录与退出方法
在AccountController中编写登录逻辑,验证用户名密码后发放Forms票据。
using System.Web.Mvc;
using System.Web.Security;
public class AccountController : Controller
{
// GET: Account/Login
public ActionResult Login()
{
return View();
}
// POST: Account/Login
[HttpPost]
public ActionResult Login(string username, string password, bool rememberMe = false)
{
// 简单演示:实际应从数据库校验
if (username == "admin" && password == "123456")
{
FormsAuthentication.SetAuthCookie(username, rememberMe);
return RedirectToAction("Index", "Home");
}
ViewBag.Error = "用户名或密码错误";
return View();
}
// 退出登录
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Login");
}
}
三、使用授权过滤器保护控制器
除了全局配置,也可以在控制器或动作上直接使用[Authorize]特性。
[Authorize]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
四、登录视图示例
对应的Login.cshtml视图可写成如下纯表单代码:
<form method="post" action="/Account/Login">
<div>
<label>用户名:</label>
<input type="text" name="username" />
</div>
<div>
<label>密码:</label>
<input type="password" name="password" />
</div>
<div>
<label><input type="checkbox" name="rememberMe" />记住我</label>
</div>
<button type="submit">登录</button>
</form>
五、注意事项
- Forms验证票据默认存放在Cookie,生产环境建议配合HTTPS防止泄露。
- timeout的单位是分钟,slidingExpiration为true时会自动延长有效期。
- 若需存储额外用户信息,可使用FormsAuthenticationTicket自定义数据。
通过以上步骤,就能在.NET MVC中基于Forms验证快速搭建用户登录与授权体系。