Frage

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?

War es hilfreich?

Lösung

What you want is

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

Andere Tipps

I think there's an overload that takes both role and username. MSDN

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top