views:

171

answers:

2

I write a controller like below:

public class AccountController : Controller
{
    public ActionResult Login(/*---*/)
    {
        GenericIdentity identity = new GenericIdentity("userName");
        GenericPrincipal principal = new GenericPrincipal(identity, new string[] { "role1", "role2" });
        this.HttpContext.User = principal;
        /*---*/;
    }
}

After login, I can get user name by User.Identity.Name in other controller. But User.IsInRole("role1") always return false.

How can I assign a value to User, I don't want to use Membership...

+1  A: 

Hm.

Using membership?

At least the lower level API. You need to assign it a principal in some event (which basically turns into a cookie and is deserialized with every call).

Details are in http://support.microsoft.com/kb/306590

Or also in http://msdn.microsoft.com/en-us/library/aa302399.aspx

TomTom
I don't want to use membership.And I don't understand about using cookie, why don't keep it in the server side like session?
ldp615
Well, first - what you want is of limited importance as you decided to use ASP.NET. As result you have to live with the design decisions made by the ASP.NET people. Sorry. Second... Cookie so that the user MAY stay logged in longer than the session persists. That simple. I hate nothing more than having to log into the same site over and over again. So, better put that into a separate cookie so you can decide how long that one stays valid. Note that you dont ahve to have the groups in there - the user's ID in the database is enough, you can always dehydrate the complete object from there.
TomTom
Thanks for your comment, I learn a lot from that!
ldp615
+2  A: 

You need to persist the user data somewhere so that all subsequent page requests have access to it. Usually you would create an authentication ticket and store it in a cookie. Then for each request you extract the data and create your IPrincipal. This can be done in the Application_AuthenticateRequest method of Global.ascx,

MVC - How to store/assign roles of authenticated users has more information on a simple way to do what you want.

David G