Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Session from HttpActionContext

Tags:

asp.net-mvc

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");
    }
}
like image 691
MuriloKunze Avatar asked Nov 20 '12 11:11

MuriloKunze


1 Answers

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
like image 51
Mihai Avatar answered Nov 15 '22 19:11

Mihai