9

I'm trying to create a permission attribute to configure in each action of my controllers so this custom attribute should take the sessionId from the user. My code is like that:

public class PermissionChecker: ActionFilterAttribute
{
    private int _permissionId { get; set; }
    private IUserSelectorService _userService { get; set; }

    public PermissionChecker(int permissionId)
    {
        _permissionId = permissionId;
        _userService = new UserSelectorService();
    }

    public PermissionChecker(int permissionId, IUserSelectorService userService)
    {
        _permissionId = permissionId;
        _userService = userService;
    }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (_userService.HasPermission(_permissionId, /* here I must pass the session["Id"]*/)){
             base.OnActionExecuting(actionContext);
             return;
        }
        throw new HttpException(401, "Unauthorized");
    }
}
MuriloKunze
  • 15,195
  • 17
  • 54
  • 82

2 Answers2

10

Use this

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if(filterContext.HttpContext.Session != null)
    {
      var id = filterContext.HttpContext.Session["Id"];          
    }
}

EDIT Given the fact that you're using MVC 4 and you don't have

public override void OnActionExecuting(ActionExecutingContext filterContext)

Try using

System.Web.HttpContext.Current.Session
Mihai
  • 2,740
  • 31
  • 45
0

if you are trying to access using ActionFilterAttribute then OnActionExecting event it wont give the accessibility of HttpContext with System.Web.Http.

Instead of that If you are trying to access using System.Web.Mvc it will provide you the current session with onActionExecting event with help of ActionExecutingContext class.

Sachin Mishra
  • 1,125
  • 1
  • 16
  • 17