Write access log in ASP NET MVC application

4

I have an ASP NET MVC website and I need to write to the database every time someone accesses the client's IP and access date, is there any way I can do that?

I do not want to record every page that the client enters, just record when to open the site, type the client opened the browser and accessed the site there I record.

Record only the second time from the same client if it accesses from another browser or if it closes the browser and reopens.

Open the site in a new tab and it is already with the site open in another tab I do not think I should count.

Thanks for the help.

    
asked by anonymous 29.09.2016 / 15:38

2 answers

2

No Global.asax , within method Session_Start() do the encoding to write by SessionId ( Session.SessionID ), an log p>

I will propose a way:

Create a database with the following layout:

CREATE TABLE [dbo].[Log](
    [SessionId] [nvarchar](24) NOT NULL,
    [SessionDataTime] [datetime] NOT NULL,
    [ServerIP] [nvarchar](15) NOT NULL,
 CONSTRAINT [PK_Log] PRIMARY KEY CLUSTERED 
(
    [SessionId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
  IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
  ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

within method Session_Start() :

protected void Session_Start()
{
    string SessionId = Session.SessionID;
    string ServerIp = Request.ServerVariables["REMOTE_ADDR"];
    DateTime SessionDataTime = DateTime.Now;
    using (SqlConnection Conn = new SqlConnection(@"Server=.\SQLExpress;Database=Db;User Id=sa;Password=senha;MultipleActiveResultSets=true;"))
    using (SqlCommand Command = Conn.CreateCommand())
    {
        Conn.Open();
        Command.CommandText = "SELECT COUNT(*) FROM Log WHERE SessionId=@SessionId";
        Command.Parameters.Add("SessionId", SqlDbType.NVarChar, 24).Value = SessionId;
        if (int.Parse(Command.ExecuteScalar().ToString()) == 0)
        {
            Command.Parameters.Clear();
            Command.CommandText = "INSERT INTO Log (SessionId,ServerIp,SessionDataTime) VALUES(@SessionId,@ServerIp,@SessionDataTime)";
            Command.Parameters.Add("SessionId", SqlDbType.NVarChar, 24).Value = SessionId;
            Command.Parameters.Add("ServerIp", SqlDbType.NVarChar, 15).Value = ServerIp;
            Command.Parameters.Add("SessionDataTime", SqlDbType.DateTime).Value = SessionDataTime;
            Command.ExecuteNonQuery();
        }
    }
}

A new record will only be inserted by renewing its SessionId .

    
29.09.2016 / 16:17
2

I will post a reply in the simplest form that I know, and that can be used in other languages.

The logic is simple. You create a cookie that will be expired per session, so every time you close the browser it will be deleted. And at your _Layout.cshtml you check if the cookie exists. If it exists it does nothing, but if it does not exist you will make a request and save whatever you want.

So, let's go to the codes.

First, let's understand a bit more about working with cookies in this question here .

This is done, let's go to our file _Layout.cshtml (or the layout file that is used on all pages) and use the following code:

   <script>
        //Função para ler o cookie
        function readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        }
        $(document).ready(function () {
            //Buscando o cookie
            var NewAccess = readCookie('NewAccess');
            //Verificando se o cookie existe
            if (!NewAccess) {
                document.cookie = "NewAccess=true; expires=0;";
                $.post('@Url.Action("SalvarLogin","Home")')//Coloque a URL para salvar os dados
            }
        });
    </script>

As the question is in Asp.Net MVC , just do this in Controller:

    [HttpPost]
    public JsonResult SalvarLogin()
    {
        //Método para salvar aqui
        return null;//Retorno que dessejar
    }

In this way you will always perform the check you want.

  

I should note that, of course, if a person clears cookies, he will consider it as a new access.

    
29.09.2016 / 16:59