Haminteu
Haminteu

Reputation: 1334

Session Start Global.asax C# ASP.NET

I have the following code:

protected void Session_Start(object sender, EventArgs e)
    {
        WindowsPrincipal p = Thread.CurrentPrincipal as WindowsPrincipal;
        string sUserAccount = HttpContext.Current.User.Identity.Name.ToString();

        HttpContext.Current.Session["WinAccount"] = sUserAccount;
    }

The code is to get the windows user name. From the session_start, I want to create a session which called WinAccount. But, when I tried to call the session from one of my page (default.aspx) which is has master page on it.

Let say, on page_load:

string sWinAccount = Session["WinAccount"].ToString();
Label1.Text = sWinAccount.ToString();

The web.config looks like:

<authentication mode="Windows"/>
<identity impersonate="false"/>
<authorization>
  <deny users="?"/>
</authorization>

Also, the properties of the project has been enabling the windows authentication mode.

When I run, it blanks. Please advise.

Thank you.

Upvotes: 1

Views: 1890

Answers (3)

NitinSingh
NitinSingh

Reputation: 2078

  1. Verify if the application is using Windows Authentication (check web.config). If you are providing custom or forms authentication, you will need to set user details on success handler, not the session start; and use CustomPrincipal rather than WindowsPrincipal .
  2. If windows authentication is enabled, the user credential will be available on the very first request (session start) and can be retrieved are you mentioned in your code. Place a debugger in session start and verify if you are retrieving it properly or not.

Upvotes: 3

Trung Le
Trung Le

Reputation: 151

Session_Start event fired when a new client start their very first request to the app, not when the user is logged in. So in your case, the HttpContext.Current.User.Identity.Name is empty at the time Session_Start is called. It worked as expected.

Upvotes: 0

Gagan Deep
Gagan Deep

Reputation: 1509

try

string sUserAccount =System.Security.Principal.WindowsIdentity.GetCurrent().Name.Tostring();

Upvotes: 1

Related Questions