双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

授权过滤器

wrost wrost 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

我自定了一个授权过滤器,验证如果没有通过就返回到登录页面/Account/Login

问题:有些操作ajax,如果没有登录,希望返回的是一个代码,比如一个整数。 该怎么做?


webconfig
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>



public class UserAuthorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!httpContext.Request.IsAuthenticated) //首要条件:必须登录,必须有身份验证票。
return false;

string controller = httpContext.Request.RequestContext.RouteData.Values["controller"].ToString();
string action = httpContext.Request.RequestContext.RouteData.Values["action"].ToString();

using (var db = new WEBVODEntities())
{
List<CtrlActRole> tempList = db.CtrlActRole.Where(a => a.ControllerName == controller && a.ActionName == action).ToList();
if (tempList.Count == 0) //如果没有找到记录,表示不需要权限控制
return true;

foreach (var ctrlActRole in tempList)
{

string roleField = ctrlActRole.RoleField; //获取对应的数据库字段

RegisteredUser oldUser = CommonUtils.GetCurrentUser();
if (oldUser == null)
return false;

var roleList = db.ExecuteStoreQuery<Role>("select top 1 * from role where " + roleField + "=1 and id={0}", oldUser.RoleId).ToList(); // 查看相应的角色,对应字段是否==true

if (roleList.Count > 0) //如果有记录,表示有权限(这个地方应该显示相应的提示,不是直接返回到登录界面)
return true;
}

}
return false;
}
}
...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
wrost
.NET社区 62,274 成员 668,968 内容