想要设置一些基于角色的依赖项(Ioc、Ninject)。但是成功登录后,用户的角色是未知的。何时何地进行注入(inject)?我可以强制初始化角色吗?还是我必须自己去取?
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
DoRolebasedObjectBinding(model.UserName); // THIS IS THE WRONG PLACE!
return RedirectToLocal(returnUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
应用程序以 HomeContoller 开始(未设置角色),成功登录后,应用程序被重定向到 de HomeController(参见上面的标准代码),现在角色已设置...
一个技巧是通过添加所有角色或额外的“公共(public)”角色来强制在 HomeController 中初始化角色
public class HomeController : Controller
{
[Authorize(Roles = "Common")]
public ActionResult Index()
{
DoRolebasedObjectBinding(User.Identity.Name);
但这会强制登录,也会强制 HomeController 作为起点。希望是一个“优雅”的地方来调用我的 DoRolebasedObjectBinding。
最佳答案
基于 Role based authentication in the new MVC 4 Internet template ,答案很简单:自己动手:
var roles = Roles.Provider;
string[] rolesArr = roles.GetRolesForUser(username);
关于asp.net-mvc - MVC 4 中的角色何时初始化?不是在成功登录后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13805774/