How to replace the session in web asp.net c #?

6

Let's see, I'll explain in more detail what happened. I have a texbox and a button; what I want is to enter data to the texbox and when I click on the button I redirect to another page getting the value of that texbox. For that I am session to store and then in the other window that will redirect me and show it.

This is the image of my codebing when I click on the button.

Now to get the value of that session and to show in a texbox what I do is in load (), like this code in my webform2.

Now when I run the application, log into my webform1.aspx and put the name in the texbox: "name1" if you redirect me to webform2.aspx and if my "name1 is displayed ".

Now the problem is that when I open another tab and put the webform1.aspx and place in the texbox nombre2 if I address to the other page and if the second name that I placed now comes back to the previous tab and update the page the name has changed and that is the problem.

How could it not be changed or what method is to replace the session ?, Since what I show is something small but according to my question because in my system the same thing happens and I would like to have the name that is placed, imagine that a user enters and registers something and is well registered with his first name that he entered but then he enters with his other user and registers everything. Now in the session it will take it with the second user and not with the first one and it would cause problems.

This is the Code of WebForm1

Front-End

 <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click"/>
    </div>
    </form>

Back-End

protected void Button1_Click(object sender, EventArgs e)
        {
            Session["usuario"] = TextBox1.Text;

            Response.Redirect("WebForm2.aspx");
        }

Webform2 Code

Front-End

<form id="form1" runat="server">
    <div>
        <asp:Label ID="lbl1" runat="server" Text="Label"></asp:Label>
    </div>
    </form>

Back-End

protected void Page_Load(object sender, EventArgs e)
        {

            if (!Page.IsPostBack)
            {

                if (Session["usuario"].ToString() == null)
                {
                    Response.Redirect("WebForm1.aspx");
                }
                else
                {
                    lbl1.Text = Session["usuario"].ToString();
                }
            }

        }

    
asked by PieroDev 02.05.2018 в 19:55
source

4 answers

3

As you said @Flxtr, you have a problem to check if the user has already been authenticated. In most of the websites that require logging, they do not allow working with two or more users at the same time from the same browser. If this is your case, they have already given you a good solution. Another similar option would be to use cookies.

In the case that this solution does not adapt to your needs because for any reason you need to be able to work with different users in the same browser, you can create the name of the sessions dynamically for each user. I'll give you an example:

Suppose we have a website with a simple login. A user name and password are requested, it is checked in database that this user exists and according to the answer, we allow it to be accessed or not.

It occurs to me that you take advantage of this query to obtain the unique identifier code of the user of your database and use it to dynamically create the name of the session variable:

int id = // identificador que obtenemos de la bbdd.
if (Session["user" + id] == null)
    Session["user" + id] = TxUsuario.Value.Trim().ToUpper(); 

Thus, in the case that the user had not previously logged in, he creates the session variable. And if he had already been logged in, we do not do anything, since the session variable already exists.

But for this to work, you must also propagate this id throughout the application (for example, you can send form login to the form home this id by url).

  

www.yourdomain.com/home?d=123

or

  

www.yourdomain.com/home/123

Then to retrieve the user's name again, simply re-create the name of the session variable dynamically:

int id = // identificador obtenido desde otro formulario mediante url.
string txUsuario = Session["user" + id].ToString();

I hope you have explained me well and that it will be useful to you.

EDITING FROM YOUR CLARIFICATION

If we adjust the example that I gave you a bit, we can adapt it to what you want. We will make this change in your click event of WebForm1:

protected void Button1_Click(object sender, EventArgs e)
{
    if (Session["usuario" + TextBox1.Text] == null)
        Session["usuario" + TextBox1.Text] = TextBox1.Text;

    Response.Redirect("WebForm2.aspx?u=" + TextBox1.Text);
}

With this, what we do is create a "single session variable" for this user, and we send the name by url to WebForm2.

And once in WebForm2:

protected void Page_Load(object sender, EventArgs e)
{
    string u = Request.QueryString["u"] == null ? "" : Request.QueryString["u"].ToString();

    if (Session["usuario" + u] == null)
        Response.Redirect("WebForm1.aspx");
    else
        lbl1.Text = Session["usuario" + u].ToString();    
}

In this way, in WebForm2 we check that we receive the value u by url and we use it to create the "single session variable". If it did not exist, we send it back to WebForm1.aspx.

Perhaps this is not the most correct way to do it, since simply using the value u that we receive by url we have the name, but as an example to clarify a bit Things are fine.

To others, in the example I have not done either but I use to encrypt all parameters that I send by url.

    
answered by 07.05.2018 / 22:28
source
6

The problem is that when entering the Login, you do not have a validation to know if the user is authenticated.

Assuming that once the user authenticates, you save the user's name in a session variable Session["AutenticatedUser"] = TxUsuario.Value.Trim().ToUpper(); (I suggest using well-known names because Session["0"] is only known to you and maintenance becomes complicated, even for you), then, in the Page_Load of the Login.aspx you should have something like this:

protected void Page_Load(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(Session["AutenticatedUser"]))
    {
        //Aquí va el código restante donde haces el login
    }
    else //Si ya está logueado, le haces un redirect a la página de inicio 
    {
        Response.Redirect("MiPaginaDeInicio.aspx");
    }
}

Likewise, when you do the Logout to the user, you must destroy the session variable so that when they log in to the login as a new user.

Logout.aspx code:

protected void Page_Load(object sender, EventArgs e)
{
    Session["AutenticatedUser"] = null;
}
    
answered by 06.05.2018 в 07:50
0

Check if your session is empty as follows

if (string.IsNullOrEmpty(Session["0"] as string))
{
    //Codigo
}
    
answered by 05.05.2018 в 18:30
0

I do the same thing I keep the user ID in session variable or in a cookie if the client wants to keep his session started, I also noticed the case you mentioned, for this I did the simplest thing that can be done, at the moment of going to the login, exactly in your event onload I eliminate the session variable or in its defect the cookie, of this form no user will be able to accede at the same time that the session of another one lasts, because the previous session will already be closed when opening the login form.

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {

        if (Request.Cookies["idUserCookie"] != null)
            {
                HttpCookie myCookie = new HttpCookie("idUserCookie");
                myCookie.Expires = DateTime.Now.AddDays(-1d);
                Response.Cookies.Add(myCookie);
            }
        if ((string)Session["IdUser"]   != null)
            Session.Remove("IdUser");
    }
}
    
answered by 09.05.2018 в 21:43