gpt4 book ai didi

asp.net-mvc - 从 HttpActionContext 获取 session

转载 作者:行者123 更新时间:2023-12-02 07:25:18 25 4
gpt4 key购买 nike

我正在尝试创建一个权限属性来在 Controller 的每个操作中进行配置,因此此自定义属性应该从用户处获取 sessionId。我的代码是这样的:

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");
}
}

最佳答案

使用这个

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

编辑鉴于您正在使用 MVC 4 并且没有

public override void OnActionExecuting(ActionExecutingContext filterContext)

尝试使用

System.Web.HttpContext.Current.Session

关于asp.net-mvc - 从 HttpActionContext 获取 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13472229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com