[mvc] 简单的forms认证
2024-08-26 05:27:08
1、在web.config的system.web节点增加authentication节点,定义如下:
<system.web>
<compilation debug="true" targetFramework="4.5.2"/>
<httpRuntime targetFramework="4.5.2"/>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880">
<credentials passwordFormat="Clear">
<user name="user" password="pwd001"/>
<user name="admin" password="pwd002"/>
</credentials>
</forms>
</authentication>
</system.web>
2,新增AccountController。
public class AccountController : Controller
{
// 用于初期表示用
public ActionResult Login()
{
return View();
} // 登录按钮
[HttpPost]
public ActionResult Login(string username, string password, string returnUrl)
{
bool result = FormsAuthentication.Authenticate(username, password);
if (result)
{
FormsAuthentication.SetAuthCookie(username, false);
return Redirect(returnUrl ?? Url.Action("Index", "Admin"));
}
else
{
ModelState.AddModelError("", "Incorrect username or password");
return View();
}
}
}
3、Login.cshtml
@{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
</head>
<body>
@using (Html.BeginForm())
{
@Html.ValidationSummary()
<p><label>Username:</label><input name="username" type="text" /></p>
<p><label>Password:</label><input name="password" type="password" /></p>
<input type="submit" value="Log in"/>
}
</body>
</html>
4、浏览器输入http://localhost:44324/Account/Login,输入web.config中定义的用户名和密码,成功就会进入Admin/Index页面。
5、其他页面如何进行认证?
1)在action中加Request.IsAuthenticated判断
public class AdminController : Controller
{
// GET: Admin
public string Index()
{
if (!Request.IsAuthenticated)
{
FormsAuthentication.RedirectToLoginPage();
}
return "welcome to Admin page!";
}
}
2)在action方法上加Authorize特性
public class AdminController : Controller
{
// GET: Admin
[Authorize]
public string Index()
{
return "welcome to Admin page!";
}
}
3)在controller上加Authorize特性(所有的action都会应用上)
[Authorize]
public class AdminController : Controller
{
// GET: Admin
public string Index()
{
return "welcome to Admin page!";
}
}
最新文章
- MySQL主从复制与读写分离
- android 开发禁止系统修改app的字体大小
- MySql 分组排序取时间最大的一条记录
- C++模板元编程 - 1 基本数据类型和运算
- linux学习之centos(一):在VMware虚拟机中安装centos6.5
- IMAQdx和IMAQ
- [原创] linux课堂-学习笔记-目录及概况
- php每秒输出一次
- artTemplate-3.0(与项目实际结合)
- 使用Xshell5连接虚拟机VMware中安装的CentOS7系统
- Sharding-jdbc实现分库分表
- 输出第n个丑数
- C#的多样性,new,sealed方法
- c++实现 给定直角停车位两个点,求取剩余两点坐标。
- windows10 VM12 安装Mac OS X 10.11
- Oracle其他简单查询
- APP-3-百度地图应用
- Oracle11g dump 部分参数解读
- 关于C++学习笔记
- 做文件上传下载时报这个错com.alibaba.fastjson.JSONException: illegal identifier : \