3

想要设置一些基于角色的依赖项(Ioc、Ninject)。但是成功登录后,用户的角色是未知的。何时何地进行注射?我可以强制初始化角色吗?还是我必须自己去取?

    [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(参见上面的标准代码),现在角色已设置......一个技巧是强制角色在HomeController 通过添加所有角色或额外的“普通”角色

public class HomeController : Controller
{
    [Authorize(Roles = "Common")]
    public ActionResult Index()
    {
        DoRolebasedObjectBinding(User.Identity.Name);

但这会强制登录,也会强制 HomeController 作为起点。希望是一个“优雅”的地方来调用我的 DoRolebasedObjectBinding。

4

1 回答 1

0

基于新 MVC 4 Internet 模板中基于角色的身份验证,答案相当简单:自己动手:

var roles = Roles.Provider;
string[] rolesArr = roles.GetRolesForUser(username);
于 2012-12-11T21:54:15.460 回答