Domanda

I created a new asp.net web application using the template that visual studio has. That type of project create a login out-of-the-box which I configured with the aspnet_regsql command to work with my database.

Now, when someone logs into the application, I need to know whether or not the login was sucessful, so I can save in Session[''] the user name among other things.

I was expecting to find a method that returns true or false but instead in the Login.aspx.cs is just the Page_Load method and I don't understand how it works.

I tried associated a onclick method that get the value of the UserName control, but obviously, that only works when the user log in for the first time, if the user check "Remember me next time" it won't work.

È stato utile?

Soluzione

The AuthenticateRequest event is raised when the user has been authenticated, however in this event you do not have access to the SessionState yet. Therefore, to save the Session you should consider the PostAcquireRequestState application event.

ASP.NET Application Life Cycle Overview for IIS 7.0

ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0

For additional info:

Example:

In global.asax

    void Application_PostAcquireRequestState(object sender, EventArgs e)
    {
        if (Context.Session != null)
        {
            Application.Lock();
            Session["user"] = User.Identity.Name;
            Application.UnLock();
        }
    }

Additionally, if you are using the LoginControl, you can handle the LoggedIn event:

ASPX

    <asp:Login runat="server" ID="login" DestinationPageUrl="~/Default.aspx" 
        FailureAction="RedirectToLoginPage"
        onloggedin="login_LoggedIn" ...>
     ....

ASPX code behind

protected void login_LoggedIn(object sender, EventArgs e)
{
    // set the Session here
}

Altri suggerimenti

The aspx web project template makes use of the asp:Login control, which does the authentication for you.

If you need to customize the login, you can roll your own username / password inputs, and then call the membership API directly, e.g.

if (Membership.ValidateUser(username, password))
{
    FormsAuthentication.SetAuthCookie(username, rememberMe);
    // Do your custom stuff here

...

You can also check to see whether the user is authenticated by using

UserPrincipal.Identity.IsAuthenticated

See MSDN for more details

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top