Nathalie De Hertogh
Nathalie De Hertogh

Reputation: 227

Create session in C#

Hi I'm creating a login form from scratch in c# using 3 tiers. I've managed to build a working form that checks if the user data is correct. If he filled in the wrong data he'll get a message. But now I need to create a session to store the id.

I've searched the web and they say you have to add Session["sessionName"]= data, but if I type Session["userId"]=s.studentNummer he doesn't recognize anything. Is it better to put the sessions in the DAL or in the DLL? I wanted to write it in the DAL (function checkLogin). Can somebody please help me?

Here's my code:

DALstudent.cs

public class DALstudent
{
    dc_databankDataContext dc = new dc_databankDataContext();

    public void insertStudent(Student s)
    {
        dc.Students.InsertOnSubmit(s);
        dc.SubmitChanges();
    }

    public bool checkLogin(string ID, string passw)
    {
        bool canlogin = false;
        var result = (from s in dc.Students
                      where s.studentNummer == ID && s.studentPasswoord == passw
                      select s).Count();
        if (result == 1)
        {
            canlogin = true;
        }
        else 
        {
            canlogin = false;
        }
        return canlogin;
    }
}

BLLstudent.cs

public class BLLstudent
{
    DALstudent DALstudent = new DALstudent();

    public void insertStudent(Student s)
    {
        DALstudent.insertStudent(s);
    }

    public string getMD5Hash(string passwd)
    {
        MD5CryptoServiceProvider x = new MD5CryptoServiceProvider();
        byte[] bs = Encoding.UTF8.GetBytes(passwd);
        bs = x.ComputeHash(bs);
        StringBuilder str = new StringBuilder();
        foreach (byte b in bs)
        {
            str.Append(b.ToString("x2").ToLower());
        }
        string password = str.ToString();
        return password;
    }

    public bool checkLogin(string ID, string passw)
    {
        bool canlogin = DALstudent.checkLogin(ID, passw);
        if (canlogin == true)
        {
            return true;
        }
        else 
        {
            throw new Exception("Uw gegevens kloppen niet");
        }
    }
}

login.aspx.cs

public partial class web_login : System.Web.UI.Page
{
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        try
        {
            BLLstudent BLLstudent = new BLLstudent();
            var loginNr = txtLoginNr.Text;
            var pass = BLLstudent.getMD5Hash(txtWachtwoord.Text);
            var passw = pass;
            BLLstudent.checkLogin(loginNr, passw);
            Response.Redirect("student/s_procedure_goedkeuring.aspx");
        }
        catch (Exception Ex) 
        {
            lblFeedback.Text = Ex.Message;
        }
    }
}

Upvotes: 18

Views: 117405

Answers (3)

JEuvin
JEuvin

Reputation: 1037

You can also use cookies for the session:

if (SessionHash != null && (!HttpContext.Current.Request.Cookies.AllKeys.Contains("hash")) {
  var cookie = new HttpCookie("hash", Convert.ToBase64String(SessionHash)) {
    HttpOnly = true
  };

  HttpContext.Current.Response.Cookies.Set(cookie);
}

// remove cookie on log out.
HttpContext.Current.Request.Cookies.Remove("hash");

Upvotes: 0

Tim M.
Tim M.

Reputation: 54417

.NET session state is handled in the presentation tier, although it is accessible in any business logic running in a web worker process (note that there is also out of process session state, but that too is managed from the presentation tier). It is rarely good practice to interact with session outside of the presentation tier.

In the business tier, session can be accessed with:

System.Web.HttpContext.Current.Session

Inside most web entities (Page, Control, View) it is simply referenced by Session.

Session is a key-based collection; you put a value in with a key, and you retrieve the same value with a key.

protected override void OnLoad( EventArgs e )
{
    Session["foo"] = "bar";
    string valueFromSession = Session["foo"].ToString();
}

Upvotes: 28

competent_tech
competent_tech

Reputation: 44971

Access to the session is only going to be available in the web application, so you will need to set and get values from the session and pass these values to your other layers from the web.

Upvotes: 0

Related Questions