定义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 { getset; }

        
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)
        {
        }

 

 

简单又方便,使代码结构更加清晰
posted on 2010-08-11 11:58  高山流水2012  阅读(3239)  评论(3编辑  收藏  举报