简体   繁体   中英

How do I get current logged in user's UserID when using ASP.NET Forms Authentication?

I am currently having trouble in ASP.NET (with Silverlight 4). I need to get the UserID of the currently logged in user, (I am using Forms Authentication). How can I get this value?

You can create a custom Forms Authentication ticket and write additional data into the ticket. Once authenticated you can then read that extra value out of the ticket.

In a lot of my apps I tend to store the user's ID and display name in there to avoid having to hit the database for every request and that works well.

To manually create a ticket looks like this:

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userState.UserId,
                                                        DateTime.Now, DateTime.Now.AddDays(10),
                                                        rememberMe, userState.ToString());

string ticketString = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketString);
if (rememberMe)
    cookie.Expires = DateTime.Now.AddDays(10);

HttpContext.Response.Cookies.Add(cookie);

You can basically pass two value - the name parameter (second) and the user data. If you want data beyond the username you can use the userdata parameter.

Then when you need to read the data make sure you're authenticated first, then you can read the user data:

if (this.User.Identity != null && this.User.Identity is FormsIdentity)                 
  userData = ((FormsIdentity)this.User.Identity).Ticket.UserData;

What you store in userData is up to you really. It can be a simple value (like your user id) or something more complex like an object that you can serialize to and from a string.

If i am correct you want to pass UserID from web application to silverlight application.

1st step:Add a web service(.asmx/.svc) in web application create a operation contract for the same.

2nd step:In web service get userId and return the same.

3 step:Add service reference in silverlight app of web service created in web

4 th step call the method using async method.

here is the link which should help you http://www.codeproject.com/Articles/37522/7-Simple-Steps-to-Connect-SQL-Server-using-WCF-fro

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM