开发者

Using session in global to update user login counter in SQL

开发者 https://www.devze.com 2023-03-02 03:20 出处:网络
Hallo, I am relatively new in both asp and sql, but has created a website where users can log in and I want to save how many times each user has been logged in.

Hallo,

I am relatively new in both asp and sql, but has created a website where users can log in and I want to save how many times each user has been logged in.

I want to use Global.asax to increment a field in my sql database each time a user goes in to the webpage, but can not get it to work.

I get no error message when I run the webpage, but the field in the database are not incremented. Am I doing it all wrong?

Global.asax is empty while I typed the following in Global.asax.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;

namespace HerningBrand
{
public class Global : System.Web.HttpApplication
{
    void Application_Start(object sender, EventArgs e)
    {
    }

    void Application_End(object sender, EventArgs e)
    {
    }

    void Application_Error(object sender, EventArgs e)
    {
    }

    void Session_Start(object sender, EventArgs e)
    {
    //INCREMENT LoginCounter//
        //connect to the db
        SqlConnection conn = new SqlConnection(WebConfigurationManager.
                        Connect开发者_开发知识库ionStrings["xxx_dbConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand("UPDATE aspnet_Users SET LoginCounter
                        =LoginCounter+1 WHERE UserName='Test'", conn);
        cmd.CommandType = CommandType.Text;
        //update where UserName is Test
        cmd.Parameters.AddWithValue("UserName", "Test");

        using (conn)
        {                
            conn.Open();   //open the connection                
            cmd.ExecuteNonQuery();   //send the query to increment the number
        }
    }

    void Session_End(object sender, EventArgs e)
    {    
    }

}

}


An ASP.NET session is separate from a user login. The session is initiated as soon as a user visits your site, before they've had a chance to login. If you're trying to test by logging in using a browser window that was already open, it won't work; you would need to close your browser (and possibly delete the cookie from your site) to get a new session.


Session_Start is called when a session starts. Typically, this is once in the lifetime of a browser window. Successive requests happen on the same session.

The function you're looking for is Application_BeginRequest. This is called once for every page that is requested.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号