打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

2013.11.08

关注
ASP.net MVC 4 中Security.FormsAuthentication验证用户的状态(匿名|已登录)
题图
编号:ylbtechASPnetMvc100010013Mvc4Security
1,功能描述
ASP.net MVC 4 下利用 System.Web.Security.FormsAuthentication类,验证用户的状态(匿名|已登录 )
以项目为例:在视图和和区域里的视图,分别都列举俩个页面(允许匿名和不允许匿名)。
2,技术与环 境
ASP.net MVC 4 下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:1, 加“[Authorize]”修饰的方法拒绝匿名。
ylb_tip:2, 提示如果是"HttpPost" 提交,则Request["param"])则再也获取不了值。
ylb_tip:3, 在返回"ReturnUrl"的时候与以前的不同。
using System.Web.Mvc;
using System.Web.Security;
namespace Mvc4Security.Controllers
{
public class AccountController : Controller
{
//
// GET: /Account/
[Authorize]
public ActionResult Index()
{
return View();
}
//
//  GET: /Account/Login
[HttpGet]
public ActionResult Login()
{
//如果是跳转过来的,则返回上一页面ReturnUrl
if (!string.IsNullOrEmpty(Request["ReturnUrl"]))
{
string returnUrl = Request["ReturnUrl"];
ViewData["ReturnUrl"] = returnUrl;  //如果存在返回,则存在隐藏标签中
}
// 如果是登录状态,则条转到个人主页
if (Session["Username"] != null)
{
return RedirectToAction("Index");
}
else
{
return View();
}
}
//
// Post: /Account/Login
[HttpPost]
public ActionResult Login(string username, string userpass,<span style="font-size: 14px;"><strong>string returnUrl</strong></span>)
{
if (username == "sunshine" && userpass == "m123")
{
//创建身份验证票证,即转换为“已登录状态”
FormsAuthentication.SetAuthCookie(username, false);
//存入Session
Session["Username"] = username;
//如果是跳转过来的,则返回上一页面ReturnUrl
if (returnUrl.Trim().Length!=0)
{
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 Mvc4Security.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
//
// GET: /Home/VipIndex
[Authorize]
public ActionResult VipIndex()
{
return View();
}
}
}
5.4  /Account/Login
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %><asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Login</asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"><h2>Login</h2><form action="/Account/Login" method="post"> <fieldset> <legend>Login</legend> <input name="returnUrl" type="hidden" value='<%=ViewData["ReturnUrl"] %>' /> username:<input id="username" name="username" value="sunshine" /><br /> password:<input id="userpass" name="userpass" value="m123" /><br /> <button type="submit">Login</button> </fieldset></form></asp:Content>
5.5  /Global  不同:有划分出了“Application_Start”方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
namespace Mvc4Security
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visithttp://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
5.6.1  /App_Start/RouteConfig.cs  不同:这里的路由参数必须是键值对。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Mvc4Security
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },namespaces:new
string[] { "Mvc4Security.Controllers" }
);
}
}
}
5.6.2  /App_Start/FilterConfig.cs 【没修改】
using System.Web;
using System.Web.Mvc;
namespace Mvc4Security
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
5.6.3  /App_Start/WebApiConfig.cs【没修改】
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace Mvc4Security
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
ASP.NET MVC:窗体身份验证及角色权限管理示例
关于Forms验证 - 科比的日志 - 网易博客
ASP.NET MVC3 Model验证总结
ASP.NET安全问题--Forms验证(后篇)--实战篇
Form验证
编程中国 - 利用ASP.NET框架创建网站登陆
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服