您的位置:首页 > 编程语言 > ASP

ASP.net MVC 中Security.FormsAuthentication验证用户的状态(匿名|已登录)

2012-08-23 17:46 811 查看
专题图

编号:ylbtechASPnetMvcSecurity100010010

1,功能描述
  ASP.net MVC下利用 System.Web.Security.FormsAuthentication类,验证用户的状态(匿名|已登录 )

以项目为例:在视图和和区域里的视图,分别都列举俩个页面(允许匿名和不允许匿名)。

2,技术与环 境
  ASP.net MVC下System.Web.Security.FormsAuthentication类,验证用户的状 态(匿名|已登录)

3,数据库设 计


4,功能截图
4.1,匿名状态下()

  4.1.1  /Home/Index  网站首页



  4.1.2  /Account/Login  登录



  4.1.3  只要是匿名用户,单击加“[NM]”修饰的地址,都会跳转到/Accout/Login页面



4.2,已登录状态下

  4.2.1  /Accout/Index  用户中心



5,代码分析
5.1,  /web.config  设置重定向登录页面

<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>


5.2,  /Controllers/AccountController.cs 账户管理控制器 ylb_tip:加“[Authorize]”修饰的方法拒绝匿名

using System.Web.Mvc;

using System.Web.Security;
namespace MvcSecurity.Controllers
{
public class AccountController : Controller
{
//
// GET: /Account/
[Authorize]
public ActionResult Index()
{
return View();
}

//
//  GET: /Account/Login

[HttpGet]
public ActionResult Login()
{
// 如果是登录状态,则条转到个人主页
if (Session["Username"] != null)
{
return RedirectToAction("Index");
}
else
{
return View();
}
}

//
// Post: /Account/Login

[HttpPost]
public ActionResult Login(string username,string userpass)
{

if (username == "sunshine" && userpass == "m123")
{

//创建身份验证票证,即转换为“已登录状态”
FormsAuthentication.SetAuthCookie(username, false);
//存入Session
Session["Username"] = username;

//如果是跳转过来的,则返回上一页面
if (!string.IsNullOrEmpty(Request["ReturnUrl"]))
{
string returnUrl = Request["ReturnUrl"];
return Redirect(returnUrl);
}
else
{
//用户个人主页
return RedirectToAction("Index");
}
}
else
{
ViewData["Tip"] = "用户名或密码有误!";
return View();
}
}

//
// GET: /Account/Logout

[HttpGet]
public ActionResult Logout()
{
//取消Session会话
Session.Abandon();

//删除Forms验证票证
FormsAuthentication.SignOut();

return RedirectToAction("Index", "Home");
}
}
}


5.3  /Controllers/HomeController.cs  首页控制器(注:区域里面的权限原理相同,在这儿就不多介绍)

using System.Web.Mvc;

namespace MvcSecurity.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/

public ActionResult Index()
{
return View();
}

//
// GET: /Home/VipIndex
[Authorize]
public ActionResult VipIndex()
{
return View();
}
}
}


6,示例 |讲解案例下载
博客园讲解: http://ylbtech.cnblogs.com/

百度文库开发文档: http://passport.baidu.com/? business&aid=6&un=ylbtech#7

谷歌开源代码下载: http://code.google.com/p/ylbtechaspnetmvc/downloads/list

请单击 “ylbtechASPnetMvcSecurity100010010”


作者:ylbtech

出处:http://ylbtech.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作

者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究

法律责任的权利。
最终目标

代码的国际化标准

示例 ylb,tech
”,最大程度地规范软件编程

开发统一,优质, 高效,易学,为建设软件强国(中国)而努

力。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: