如何在PermisoAttribute中获取用户名MVC for Represent

时间:2017-03-28 20:36:35

标签: asp.net-mvc

我有PermisoAttribute这样的

public class PermisoAttribute : ActionFilterAttribute
        {
            public string username { get; set; }
            public int ProgramId { get; set; }
            public int ModuleId { get; set; }

            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                base.OnActionExecuting(filterContext);

                if (!permisos(this.username,this.ProgramId,this.ModuleId))
                {
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                    {
                        controller = "Home",
                        action = "Denegado"
                    }));
                }
            }
        }

并且这使用permisos来知道用户是否拥有权限,该类返回true或false。但是当我在控制器中使用PermisoAttribute时,我会发现行为错误

  

错误CS0120非静态字段需要对象引用,   方法或属性'Controller.User'

我像这样使用permissoAttribute

[HttpGet]
[Permiso(username = User.Identity.Name, ModuleId = 3, ProgramId = 2)]
public ActionResult Transactions()
{
  //do something here 
}

我使用此代码User.Identity.Name将用户发送到PermisoAttribute。

1 个答案:

答案 0 :(得分:0)

只是更改ActionFilterAttribute,因为没有收到用户名这样的

  public class PermisoAttribute : ActionFilterAttribute
        {
            public string username = HttpContext.Current.User.Identity.Name; // { get; set; }
            public string Program { get; set; }
            public string Module { get; set; }

            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                base.OnActionExecuting(filterContext);

                if (!permisos(this.username, this.Program, this.Module))
                {
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                    {
                        controller = "Home",
                        action = "Denegado"
                    }));
                }
            }
        }

并获取HttpContext.Current.User.Identity.Name的用户名,并且对于调用PermisoAttribute,只需发送[Permiso(Module = "modulename", Program = "programaname")]