Shahin
Shahin

Reputation: 12843

ASP.NET Membership Get logged on user

I had define a username in and I added it to a role.

Now, I use this code to check if user valid:

if (Membership.ValidateUser(txtUsername.Text, txtPassword.Text)) {
    FormsAuthentication.SetAuthCookie(txtUsername.Text, false);
    if (Roles.GetRolesForUser(txtUsername.Text).Any(role => role == "Admin")) {
        Page.Response.Redirect(ResolveUrl("~/Admin/Products.aspx"));
    }
    txtUsername.Text = "";
}

After that, I want to check in Products.aspx page if user is in a role or not. I wrote this code but it returns my local Windows username :

Context.User.Identity.Name

I thinks it should returns logged on user.

After that I will check with this code :

  if (!Context.User.IsInRole("Admin"))
        {
            Response.Redirect(ResolveUrl("~/Default.aspx"));

        }


What's wrong with my code? How can I check for that if logged on user is in specific role?

Upvotes: 3

Views: 4266

Answers (2)

amiry jd
amiry jd

Reputation: 27585

Do you set the authentication-mode to Forms?

Web.config:

<authentication mode="Forms">
</authentication>

Also you should use Page.User.Identity.Name instead of Context.User.Identity.Name.

Upvotes: 4

Josh Darnell
Josh Darnell

Reputation: 11433

I believe you just need to use Page.User.Identity.Name, instead of Context.

Let me know if that does it, I've made that mix-up before =)

Upvotes: 2

Related Questions