Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Empty String ?

Status
Not open for further replies.

jpfo

Programmer
Feb 11, 2002
6
0
0
PT
Can anyone tell me why this happens?...

I have this class

Code:
using System; 
using System.Security; 
using System.Security.Principal; 

public class Username : System.Web.HttpApplication 
{ 
    public Username() 
    { 
        strUserName = User.Identity.Name.ToString(); 
    } 
    static public string strUserName = ""; 
}

That i call in any form like this:

Code:
public class WebForm1 : System.Web.UI.Page 
{ 
    protected System.Web.UI.WebControls.Label lblUserName;     
    private void Page_Load(object sender, System.EventArgs e) 
    { 
        string strUserName = Username.strUserName; 
        lblUserName.Text=strUserName; 
     } 
}

But the lblUsername.text (label) returns "".

I'am a newbie in C#, so fell welcome to help me ;P

PS. Yes i have inclued in the web.config the authentication Windows mode and config the IIS ( works ok since the not autorized users got a error page and the autorized user can acess the page )
 
Try declaring the variable before you make the constructor.
 
i know this is quite late, and i m sure you figured it out yourself in the meantime.

the prob is, that a static field does not call the constructor, thus the initialization wont take place
 
gashcud is correct. Static values are initialized essentially at compile-time (since they're static, that means that instances of the class can't change them).

Since it looks like you're trying to find out who sent you the request for your WebForm, why not look at the User property off System.Web.UI.Page? This returns you an IPrinciple interface, which will be either a GenericPrinciple or WindowsPrinciple object. Both of them have an Identity property, which returns an IIdentity interface. The IIdentity interface specifies that all it's implementors (FormsIdentity, GenericIdentity, PassportIdentity, and WindowsIdentity) will provide a Name method.
Code:
lblUserName.Text = this.User.Identity.Name.ToString();
You can use the "this" to do this because your WebForm1 inherits from System.Web.UI.Page.

I don't know if you care what format the Name value is (it seems to be different for all 4 implementors of IIdentity), but if you did you could use the GetType() method to find out.
Code:
if (this.User.Identity.GetType() == "WindowsIdentity") {
   lblUserName.Text = "Windows User: " + this.User.Identity.Name.ToString();
}
Chip H.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top