Question

In my .net application I created a label in my navigation bar that calls the header variable from the server as the username. This works fine but when I try to pass that variable to my other pages it doesn't work.

I decided the best option would be to use a querystring instead of session variables. So here is my code (disclaimer: first time using querystrings so not sure if it is used correctly or not)

aspx - Main page w/ username:

<asp:Label runat="server" ID="Username" Text="User"></asp:Label>

cs - Main page:

Username.Text = Request.Headers["displayname"];
Response.Redirect("About.aspx?Parameter=" + Username.Text);

aspx - About page needs/username:

<asp:Label runat="server" ID="Username" Text="User"></asp:Label>

cs - About page:

Username.Text = Request.QueryString["Parameter"].ToString();

I know some of this is probably wrong so any suggestions on the best way to do this or what I am doing wrong would really help me fix this problem.

EDIT - added my cs from both pages

Main:

   protected void Page_Load(object sender, EventArgs e)
        {
            Username.Text = Request.Headers["displayname"];
            DateUpdated.Text = DateTime.Now.ToString("M/dd/yy");
            Session["name"] = "Username.Text";
        }

About:

protected void Page_Load(object sender, EventArgs e)
        {            
            Username.Text = (string) (Session["Username"]);
            DateUpdated.Text = DateTime.Now.ToString("M/dd/yy");
        }
Was it helpful?

Solution

Use session instead,

Save to session: Session["UserName"] = "MyUserName" (wherever you're getting it)
You'll probably want to do this wherever the user is logging in.

Retrieve/Set it to your label : Username.Text = (string)(Session["UserName"]);

This way you have access to it wherever you need it and someone can't simply manually change the query string to impersonate another user.

In order to use session, you must enable it using the session state node in web.config, the in-process mode will probably suit your needs the best. Put the following node in the <system.web> node of your web.config:

<sessionstate 
      mode="inproc"
      cookieless="false" 
      timeout="20" 
/>

Edit based on your code samples, see how I am setting the "UserName" session var and retrieving it later:

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack) {
               Username.Text = Request.Headers["displayname"];
               DateUpdated.Text = DateTime.Now.ToString("M/dd/yy");
               Session["Username"] = Request.Headers["displayname"];
            }
        }

protected void Page_Load(object sender, EventArgs e)
        {     
            if (!IsPostBack) {
               Username.Text = (string) (Session["Username"]);
               DateUpdated.Text = DateTime.Now.ToString("M/dd/yy");
            }
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top