編號: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,string returnUrl)
{
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”方法。
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,
// visit http://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 }
);
}
}
}
| 6,示例 |講解案例下載 |
博客園講解: http://ylbtech.cnblogs.com/
百度文庫開發文檔: http://passport.baidu.com/? business&aid=6&un=ylbtech#7
谷歌開源代碼下載: http://code.google.com/p/ylbtechaspnetmvc/downloads/list
請單擊 “ylbtechASPnetMvcSecurity100010010”
百度網盤 http://pan.baidu.com/s/1i49zn73
請單擊 “ASPnetMvcSecurity100010010”
| 作者:ylbtech 出處:http://ylbtech.cnblogs.com/ 本文版權歸作者和博客園共有,歡迎轉載,但未經作 者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究 法律責任的權利。 |
| 最終目標 |
“代碼的國際化標准 示例 ylb,tech”,最大程度地規范軟件編程 開發統一,優質, 高效,易學,為建設軟件強國(中國)而努 力。
