【问题标题】:Startup Class IsInRole .net core启动类 IsInRole .net 核心
【发布时间】:2019-01-31 15:50:25
【问题描述】:

我在我的 Startup 类的 ConfigureServices 中工作。我想运行我理解的 IsInRole() 来填充操作:

但是,运行:

System.Security.Principal.IPrincipal.IsInRole("BRV_Projects_Edit");

显然不成功,因为 this 指的是接口,而不是实现该接口的实例?

我的问题是,在 ConfigureService 的上下文中,我定义了一个自定义属性,如何访问(注入?)当前用户的 Principal。

【问题讨论】:

  • 不,你不能,因为启动代码在它开始监听网络请求之前运行并且还没有任何 httpcontext
  • HttpContext.User aka claimprincipal 当前用户在身份验证中间件运行之前不存在。
  • 有什么方法可以将 HttpContext 放入 ActionFilterAttribute 中?
  • 感谢现在查看,看起来 MVC4 与 .net core 存在一些差异

标签: c# asp.net-core .net-core


【解决方案1】:

根据上面的反馈,User.InRole 在管道中此时无法访问,但可以通过创建 ActionFilterAttribute 进行访问。

ActionFilterAttribute 使 OnActionExecuting 可用,Get User Name on Action Filter 与这篇文章非常相似,除了与 .net 核心相关的更改

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.Controller is Controller controller)
        {
            controller.ViewBag.CanEdit = filterContext.HttpContext.User.IsInRole("group1");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-21
    • 2017-10-23
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 2022-10-16
    相关资源
    最近更新 更多