问题描述
需求是这样:需要根据用户的appid进行判断,看是否有访问某个action的权限,由于在controller中只公开了index,其他action对用户而言是不可知也不可直接访问,代码示例如下:publicJsonResultIndex(){JsonResultresult=newJsonResult();switch(Method.ToLower()){case"getteacherbyuserid":result=GetTeacherByUserId();break;default:result=BuildErrorMessage(string.Format("{0}.{1}方法不存在","TeacherController",Method));break;}returnresult;}[NonAction]publicJsonResultGetTeacherByUserId(){ResultDataresultData=newResultData();stringuserid="",error="";if(!GetSafeString("userid",refuserid,outerror)){resultData.Error=error;resultData.State=0;returnJson(resultData);}try{resultData.Data=_teacherService.GetTeacherByUserId(userid);resultData.State=1;}catch(Exceptionex){resultData.State=0;resultData.Error=ex.Message;}returnJson(resultData);}
然后我写了一个ActionFilterAttribute,在其中对发来请求的用户做了判断,代码大致如下:publicclassMethodAuthorizationFilter:ActionFilterAttribute{///<summary>///需要验证的Action名称集合('|'隔开)///</summary>publicstringMethod{get;set;}///<summary>///Action执行之前///</summary>///<paramname="filterContext"></param>publicoverridevoidOnActionExecuting(ActionExecutingContextfilterContext){//若没有配置需要验证的Action,则该Controller所有方法都需进行权限校验if(string.IsNullOrEmpty(Method)){VerifyRequest(filterContext);}else{//需要验证的Action集合varactionList=Method.ToLower().Split('|');//请求的Action名称stringactionName=filterContext.HttpContext.Request.Form["method"];if(actionList.Contains(actionName.ToLower())){VerifyRequest(filterContext);}}base.OnActionExecuting(filterContext);}///<summary>///请求权限校验///</summary>///<paramname="filterContext"></param>privatevoidVerifyRequest(ActionExecutingContextfilterContext){//下略}}
然后问题来了,如果我将这个Attribute加在index上,是可以工作的,如果加在GetTeacherByUserId上则不起作用,请高人指点,分数不多,尚请海涵。