您的位置:首页 > 其它

MVC中如何利用filter实现权限管理

2010-08-11 11:58 369 查看
定义filter:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web;
using System.Web.Routing;
using Vslea.Models;

namespace Vslea.Filters
{
public class RoleAttribute:ActionFilterAttribute,IAuthorizationFilter
{
public RoleAttribute(RoleTypeEnum roleType)
{
this.RoleType = roleType;
}
public RoleTypeEnum RoleType { get; set; }

public void OnAuthorization(AuthorizationContext filterContext)
{
HttpContextBase b = filterContext.RequestContext.HttpContext;
UserModel model = b.Session["User"] as UserModel;
if (model != null)
{
if (model.RoleType != this.RoleType)
{
filterContext.Result = new RedirectToRouteResult("default", new RouteValueDictionary(new { controller = "Shared", action = "Error" }));
}
}
}
}
}

在controller中:

[AcceptVerbs(HttpVerbs.Get)]
[Role(RoleTypeEnum.Admin)]
public ActionResult NewCustomer(int? customerId)
{
}

简单又方便,使代码结构更加清晰
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: