关于全局验证

i08kingdom 2018-11-23 09:53:18
不知道怎么描述问题
我就想实现验证用户是否有权限访问页面,所以写了个过滤器,却未被执行
初学者只知皮毛,求解勿喷


/// <summary>
/// 判断用户角色是否有权限访问页面
/// </summary>
public class CheckRole : ActionFilterAttribute
{
public string[] Roles { get; set; }
public bool IsCheck { get; set; }
private YunChenDistributionContext db = new YunChenDistributionContext();
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!IsCheck)
return;

string openid = HttpContext.Current.Session["WXOpenId"].ToString();
bool isRole = false;

foreach(string role in Roles)
{
switch (role)
{
case "shoper":
var shop = db.Shops.FirstOrDefault(m => m.WXOpenId == openid);
if (shop != null)
isRole = true;
break;
case "customer":
var customer = db.Customers.FirstOrDefault(m => m.WXOpenId == openid);
if (customer != null)
isRole = true;
break;
case "distributor":
var distributor = db.Distributors.FirstOrDefault(m => m.WXOpenId == openid);
if (distributor != null)
isRole = true;
break;
case "staff":
var staff = db.Staffs.FirstOrDefault(m => m.WXOpenId == openid);
if (staff != null)
isRole = true;
break;
}
}

if(isRole)
{
//如果角色没有注册,则跳转到首页
HttpContext.Current.Session["Alert"] = "您无权访问此页面!";
filterContext.Result = new RedirectResult("/");
return;
}

base.OnActionExecuting(filterContext);
}
}


然后我在FilterConfig添加了如下代码
filters.Add(new CheckRole() { IsCheck = true , Roles = new[] { "staff", "distributor", "customer", "shoper" } });//允许"staff", "distributor", "customer", "shoper"这四个角色访问

调试发现过滤器并没有被执行,求教
...全文
791 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
风衣笛手 2018-11-28
  • 打赏
  • 举报
回复
需要在Global.asax的Application_Start()里注册FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
i08kingdom 2018-11-23
  • 打赏
  • 举报
回复
找到问题了

问题不是过滤器本身代码的问题

问题是然后我在FilterConfig添加了如下代码
filters.Add(new CheckRole() { IsCheck = true , Roles = new[] { "staff", "distributor", "customer", "shoper" } });//允许"staff", "distributor", "customer", "shoper"这四个角色访问

但是我希望某个action只允许某一个角色访问
所以我在action前又添加了[CheckRole(Roles = new[] { "shoper" }, IsCheck = true)]
结果就没有执行了,请问这怎么办
i08kingdom 2018-11-23
  • 打赏
  • 举报
回复
引用 1 楼 正怒月神 的回复:
你断点调试了吗?

断点调试了,每行代码都点了,没有一行代码被执行
正怒月神 版主 2018-11-23
  • 打赏
  • 举报
回复
你断点调试了吗?

62,025

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧