简体   繁体   中英

Identity user after they have logged in .net 4.5

I need some help here, I am trying to identify a user after they have logged in. My code works ok apart from the where clause. How do you identify a user, I am basically trying to say where UserName == loginName give me the full record. Then from the record I can pull out the GarageID, any help or pointers much appreciated.

  private void FindGarageID()
    {
        System.Security.Principal.WindowsIdentity identity = Context.Request.LogonUserIdentity;

        string loginName = identity.Name;

        using (tyrescannerdatabaseEntities dbcontext = new tyrescannerdatabaseEntities())
        {

            garage = (from r in dbcontext.AspNetUsers

                          where r.UserName == loginName

                          select r).FirstOrDefault();

            if (!garage.GarageID.Equals(null))
            {
                garageID = (int)garage.GarageID;
            }
            else
            {
                garageID = 1;
            }
       }

So here is how I would do this. I would create a static class called Session. This just encapsulates the accessing of session variables for me.

public static class Session
{
      public static string UserName
      {
           get { return (JsonWhereClause)HttpContext.Current.Session["UserName"]; }
           set { HttpContext.Current.Session["UserName"] = value; }
      }

}

Then when the user logs in, I would do this.

 Session.UserName = ""//User inputed username

This would then make your code be this.

private void FindGarageID()
{
    string loginName = Session.UserName;

    using (tyrescannerdatabaseEntities dbcontext = new tyrescannerdatabaseEntities())
    {

        garage = (from r in dbcontext.AspNetUsers

                      where r.UserName == loginName

                      select r).FirstOrDefault();

        if (!garage.GarageID.Equals(null))
        {
            garageID = (int)garage.GarageID;
        }
        else
        {
            garageID = 1;
        }
   }

Note that the Session will only be available on the webserver, so if you have a service you would need to pass the username to the service.

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