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!";
}
}

最新文章

  1. MySQL主从复制与读写分离
  2. android 开发禁止系统修改app的字体大小
  3. MySql 分组排序取时间最大的一条记录
  4. C++模板元编程 - 1 基本数据类型和运算
  5. linux学习之centos(一):在VMware虚拟机中安装centos6.5
  6. IMAQdx和IMAQ
  7. [原创] linux课堂-学习笔记-目录及概况
  8. php每秒输出一次
  9. artTemplate-3.0(与项目实际结合)
  10. 使用Xshell5连接虚拟机VMware中安装的CentOS7系统
  11. Sharding-jdbc实现分库分表
  12. 输出第n个丑数
  13. C#的多样性,new,sealed方法
  14. c++实现 给定直角停车位两个点,求取剩余两点坐标。
  15. windows10 VM12 安装Mac OS X 10.11
  16. Oracle其他简单查询
  17. APP-3-百度地图应用
  18. Oracle11g dump 部分参数解读
  19. 关于C++学习笔记
  20. 做文件上传下载时报这个错com.alibaba.fastjson.JSONException: illegal identifier : \

热门文章

  1. Navicat操作数据库时一直显示加载中
  2. Python发送QQ邮件
  3. 潭州课堂25班:Ph201805201 django框架 第十课 GET,POST 请求 文件上传,HttpResponse,cookie (课堂笔记)
  4. vue动态切换页面
  5. GitHub用法
  6. js间隔一段时间打印数据库中的值
  7. table 变量
  8. MySQL中exists和in的区别及使用场景
  9. IIS安装、配置 发布网站 报错解决方案
  10. python写入excel(xlswriter)--生成图表