ASP.NET MVC Filter 类切面 Session 存储 权限控制:
{
public class RoleFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
//没有登录执行的操作
if (!(filterContext.RouteData.Values["controller"].Equals("Account") && filterContext.RouteData.Values["action"].Equals("LogOn")))
{
filterContext.HttpContext.Response.Redirect("/Account/LogOn");
}
}
else
{
//判断是否存在注册用户
FormsIdentity user = (FormsIdentity)HttpContext.Current.User.Identity;
//判断是否存在页面权限
//采用Session存储信息
//String UserRoles = Convert.ToString(System.Web.HttpContext.Current.Session["UserRoles"]);
//采用Cooke存储信息
String UserRoles = "";
if (System.Web.HttpContext.Current.Request.Cookies["RolesCooke"] != null)
{
UserRoles = Convert.ToString(System.Web.HttpContext.Current.Request.Cookies["RolesCooke"].Value);
}
bool roleto = false;
for (int ri = 0; ri < Rolestr.Count();ri++ )//au.Count > 0)
{
string model = filterContext.RouteData.Values["controller"].ToString();
string action = filterContext.RouteData.Values["action"].ToString();
if (UserRoles.Contains("*.*")) //Controller.*
{ roleto = true; break; }
if (UserRoles.Contains(","+model + ".*")) //Controller.*
{ roleto = true; break; }
if(Rolestr[ri].Equals(model+"."+action))
{ roleto = true; break; }
}
if (!roleto)
{
if (!(filterContext.RouteData.Values["controller"].Equals("Account") && filterContext.RouteData.Values["action"].Equals("LogOn")))
{
filterContext.HttpContext.Response.Redirect("/Account/LogOn");
}
}
}
}
}
}
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
//采用Cooke进行信息存储
HttpCookie cookie = new HttpCookie("RolesCooke");//初使化并设置Cookie的名称
DateTime dt = DateTime.Now;
TimeSpan ts = new TimeSpan(0, 1, 0, 0, 0);//过期时间为1小时 初始化为指定的天数、小时数、分钟数、秒数和毫秒数
cookie.Expires = dt.Add(ts);//设置过期时间
cookie.Value = ",Home.Index,Home.About";
Response.AppendCookie(cookie);
//Session 进行信息存储
//System.Web.HttpContext.Current.Session["UserRoles"] = ",Home.Index,Home.About";
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
Global.asax.cs //添加全局filter控制
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new RoleFilter());
}