【问题标题】:How to pass Data from Controller to layout using ActionFilterAttribute in Asp.Net Core MVC如何在 Asp.Net Core MVC 中使用 ActionFilterAttribute 将数据从控制器传递到布局
【发布时间】:2021-10-15 10:21:09
【问题描述】:

在我的网站上,用户根据登录时的三件事进行身份验证

  • 用户ID
  • 角色 ID
  • 站点 ID

现在检查所有这些并用户登录后,问题是,例如,如果用户在站点 1 上具有管理员角色,并且在站点 2 中具有正常角色,如果在登录时他选择站点 2,他具有正常角色。他以管理员身份登录。所以我想在登录时捕获角色 id 并能够在我的布局视图中使用它。我在搜索“ActionFilterAttribute”时发现了这一点,这使我可以在任何地方使用 ViewBage。但是现在我如何将这个登录的用户角色 ID 传递给这个“ActionFilterAttribute”并将它添加到 ViewBag 并能够在我的网站上的任何地方使用它。我没有找到任何可以帮助我实现这一目标的方法。

这是我在 AccountController 中的登录操作


        [HttpPost]
        [AllowAnonymous]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = await userManager.FindByNameAsync(model.userName);
                var id = await userManager.FindByIdAsync(user.Id);
                var query = (from st in dbContext.UserRoles
                            where st.UserId == user.Id
                            select st.RoleId).ToList();

                
                if (user != null && AuthenticateAD(model.userName, model.Password))
                {
                    for (int i=0; i<query.Count;i++)
                    {
                        if (await applicationUserManager.IsInRoleByIdAsync(id, query[i], 
                             model.sites))
                        {
                            if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                            {
                                return Redirect(returnUrl);
                            }
                            else
                            {
                                model.RoleId = query[i];
                                await signInManager.SignInAsync(user, false);
                                return RedirectToAction("Index", "Home", query[i]);
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("", "Not Authorized");
                        }
                    }
                    
                }
                else
                {
                    ModelState.AddModelError("", "Invalid username or password.");
                }
            }
            return View(model);
        }

这是我的布局,我检查登录用户是否在角色管理员中。现在,如果我从 Login 传递了角色 ID,我希望能够在这里使用它

    @if (signInManager.IsSignedIn(User) && User.IsInRole("Admin") )
     {
        Here it shows ManageUser option
     }

验证AD

      public bool AuthenticateAD(string username, string password)
        {
            using (var context = new PrincipalContext(ContextType.Domain, 
               "xxx.com"))
            {
                return context.ValidateCredentials(username, password);
            }
        }         

如果有任何方法可以将角色 ID 传递给布局,那就太好了。提前感谢任何回答的人

我找到的ActionFilterAttribute 代码在这里ActionFilterAttribute @Mohammad Karimi

【问题讨论】:

  • 您能分享一下您是如何登录用户并在方法AuthenticateAD 中启动用户会话的吗?
  • @Chetan 它使用用户原则在 Active Directory 上验证用户群。我会发布它

标签: c# asp.net-core model-view-controller asp.net-core-mvc


【解决方案1】:

您可以添加一个 BaseController,然后您应该将 Base Controller 继承给您的其他控制器。如果您每次都将 OnActionExecuting 添加到您的 BaseBontroller 是否可行。然后就可以通过 ViewBag 将数据传递给 Layout。

基础控制器

    public class BaseController : Controller
        {
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                ViewBag.Test = "Test";
            }
        }

家庭控制器

    public class HomeController : BaseController
    {
        public IActionResult Index()
        {          
            return View();
        }
    }

布局

   @{ 
      var test = ViewBag.Test;
    }

【讨论】:

  • 谢谢您的回答但是我怎样才能将我从登录页面获得的角色 ID 传递给这个 baseController? .. 如果我理解正确,我可以在 BaseController 中设置一个 ViewBag 并在任何地方使用它,但我希望它来自 Login 的 viewBag 的值,即角色 ID。你可以在我的代码中检查它在查询[i]
【解决方案2】:

你可以试试这个吗?

BaseController

 public class BaseController : Controller
    {
        public int RoleId = 0;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //Read RoleId from cookie or session;
            ViewBag.Test = "";//set cooki value
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            ViewBag.Test = RoleId;
            //Set RoleId to cookie or session
        }
    }

HomeController

 public class HomeController : BaseController
    {
        public IActionResult Index()
        {
            RoleId = 15;
            return View();
        }
    }

【讨论】:

    猜你喜欢
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多