Write access log to ASP NET MVC application

Asked

Viewed 419 times

4

I have an ASP NET MVC site and I need to record it in the database every time someone accesses by recording the client’s IP and access date, is there any way to do this?

I don’t want to record every page that the customer enters, just record when opening the site, like the customer opened the browsed and accessed the site there I record.

Record only the second time of the same client if it is accessed by another browser or if it closes the browser and opens again.

Open the site in a new tab and it is already with the site opened in another tab I believe I should not count.

Thanks for the help.

  • http://answall.com/q/52240/101. Nothing specific, but neither is the question. Either it is duplicate or it seems broad.

  • Could you add more details? Does your site have login? It will count if you access any screen?

  • My site has no login, any screen account if it is the first time the site is accessed. if he accesses www.meusite.com.br then account if it is the first time, if he accesses direct www.meusite.com.br/Minhapagina then account if it is the first time

  • I don’t know how to identify if it’s the first time to record in the bank, that’s all I need. I’m seeing here what I might be able to do with Actionfilters, but how can I make an if by checking if it’s the customer’s first time on the site?

2 answers

2


In the Global.asax, within the method Session_Start() do the encoding to write by SessionId (Session.SessionID), one log of information.

I’ll 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 the 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 registration shall be entered only upon the renewal of its SessionId.

  • 1

    This Session_start() solved my problem, I did not use your code completely pq use Mysql but Session_start() saved. Thank you

  • Opa @Mauricioferraz, thanks, I just didn’t do it with Mysql because in the question I didn’t have a tag saying this... if I had implemented but, I’m sure you already had a routine ... !

2

I will post an answer in the simplest form I know, which can be used in other languages.

The logic is simple. You create a cookie which will be expired by Session, so whenever you close the browser it will be deleted. And in your _Layout.cshtml you make the check if the cookie exists. If it exists it does nothing, but if it does not exist you make a request and save what you want.

So let’s go to the codes.

First, let’s understand a little more about how to work with cookies in this question here.

That done, let’s go to our archive _Layout.cshtml (or the layout file that is used on all pages) and we will 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>

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

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

This way you will always perform the check you want.

I must point out that, logically, if the person cleans the cookies, he will consider as a new access.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.