给定UserName的字符串,我该如何检查该用户是否为IsInRole?

时间:2012-04-20 13:39:28

标签: asp.net-mvc asp.net-mvc-3 membership-provider isinrole

我试图在完全“登录”到我正在构建的网站之前检查给定用户是否有角色。通常我会使用代码:

User.IsInRole("CustomRole")

但是在这种情况下,该行总是产生“假” - 我相信这是因为使用User.IsInRole,用户必须已经完全登录。我试图在LogOn方法中检查这条信息我的帐户控制器,所以用户尚未登录(我认为)。

如何返回用户对象,以便我可以执行下面尝试执行的操作:

public ActionResult LogOn(LogOnModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(model.UserName, model.Password))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

            // Need to identify the user because the "User" is not officially 'logged in' yet and cannot be accessed via "User.IsInRole" - am I correct in this understanding
            MembershipUser u = Membership.GetUser(model.UserName);
            if (u.IsInRole("Administrator"))

. . . . truncated

上面的代码会引发以下错误:

'System.Web.Security.MembershipUser' does not contain a definition for 'IsInRole' and no extension method 'IsInRole' accepting a first argument of type 'System.Web.Security.MembershipUser' could be found (are you missing a using directive or an assembly reference?)

MembershipUser u = Membership.GetUser(model.UserName)显然没有返回一个我可以使用IsInRole的对象,有什么提示吗?

2 个答案:

答案 0 :(得分:5)

你想要的是

var authorized = Roles.IsUserInRole(username, roleName);

答案 1 :(得分:0)

我认为有一个带有角色和用户名的重载。 MSDN