asp.net-mvcasp.net-mvc-3membership-providerisinrole

Given the string of the UserName, how can I check if that user IsInRole?


I am attempting to check if a given user has a role before they are fully 'logged in' to the site I am building. Typically I would use the code:

User.IsInRole("CustomRole")

But in this situation that line always yields "false" - I believe this is because to use User.IsInRole, the user has to already be fully logged in. I am attempting to check this piece of information within the LogOn method of my Account controller, so the user is not yet logged in (I think).

How would I return a user object so that I could do what I am attempting to do below:

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

The above code throws the following error:

'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) is apparently not returning an object I can use IsInRole with, any tips?


Solution

  • What you want is

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