문제

저는 초보자이며 C# 2005와 함께 ASP .NET 2.0을 사용하여 웹 사이트를 개발하고 있습니다. NO를 계산하기 위해 시설을 추가하고 싶습니다. 내 웹 사이트 방문자. Global.asax를 사용 하여이 기능을 추가하기 위해 기본 정보를 수집했습니다. System.web 섹션에서 라인을 추가하여 Web.config를 수정했습니다.

방문자 수를 유지하기 위해 테이블을 사용하고 있습니다. 하지만 작업을 완료하는 방법을 모르겠습니다. My Default Global.asax 파일에는 다른 섹션 Application_start, application_end, application_error, session_start 및 session_end가 포함되어 있습니다. application_start 섹션에서 카운터의 현재 값을 추출하고 전역 변수에 저장하려고했습니다. Session_Start에서 카운터를 증가시키고 Application_end에서 수정 된 값을 테이블에 작성합니다.

나는 공개 서브 루틴/기능을 사용하려고 노력했습니다. 그러나 그 서브 루틴은 어디에 배치해야합니까? Global.asax 자체에 서브 루틴을 추가하려고했습니다. 그러나 이제 Global.asax의 data.sqlclient에 대한 참조를 추가 할 수 없으므로 오류가 발생하고 있으며 기능을 구현하려면 SQLConnection, SQLCommand, SQLDATAREADER 등에 대한 참조가 필요합니다. 각 서브 루틴에 대한 클래스 파일을 추가해야합니까? 저를 안내 해주세요.

또한 웹 사이트에 추적 기능을 구현하고 웹 사이트 방문자의 IP 주소, 브라우저, 방문 날짜 및 시간, 화면 해상도 등을 저장하고 싶습니다. 어떻게하니?

제안을 기다리고 있습니다.

Lalit Kumar Barik

도움이 되었습니까?

해결책

Google 웹 로그 분석 스크립트는 정확히 필요한 것입니다. 세션은 크롤러도 열립니다.

다른 팁

순진한 구현을 위해서는 사용자 정의 httpmodule을 사용할 수 있습니다. 응용 프로그램에 대한 각 요청에 대해 다음과 같습니다.

  1. request.cookies에 추적 쿠키가 포함되어 있는지 확인하십시오
  2. 추적 쿠키가 존재하지 않으면 이것은 아마도 새로운 방문자 일 것입니다 (또는 그렇지 않으면 쿠키가 만료되었습니다 - 참조).
  3. 새 방문자의 경우 방문자 통계를 기록한 다음 방문자 수를 업데이트하십시오.
  4. 방문자에게 다시 전송되는 응답에 추적 쿠키를 추가하십시오. 이 쿠키가 만료 기간이 다소 긴 기간을 갖도록 설정하고 싶으므로 쿠키가 만료 된 귀환 사용자와 많은 "거짓 양성"을 얻지 못합니다.

다음은 아래의 골격 코드입니다 (AS를 저장하십시오 STATSCOUNTER.CS):

using System;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Transactions;

namespace hitcounter
{
    public class StatsCounter : IHttpModule
    {
        // This is what we'll call our tracking cookie.
        // Alternatively, you could read this from your Web.config file:
        public const string TrackingCookieName = "__SITE__STATS";

        #region IHttpModule Members

        public void Dispose()
        { ;}

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.PreSendRequestHeaders += new EventHandler(context_PreSendRequestHeaders);
        }

        void context_PreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            HttpResponse response = app.Response;
            if (response.Cookies[TrackingCookieName] == null)
            {
                HttpCookie trackingCookie = new HttpCookie(TrackingCookieName);
                trackingCookie.Expires = DateTime.Now.AddYears(1);  // make this cookie last a while
                trackingCookie.HttpOnly = true;
                trackingCookie.Path = "/";
                trackingCookie.Values["VisitorCount"] = GetVisitorCount().ToString();
                trackingCookie.Values["LastVisit"] = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss");

                response.Cookies.Add(trackingCookie);
            }
        }

        private long GetVisitorCount()
        {
            // Lookup visitor count and cache it, for improved performance.
            // Return Count (we're returning 0 here since this is just a stub):
            return 0;
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            HttpRequest request = app.Request;

            // Check for tracking cookie:
            if (request.Cookies[TrackingCookieName] != null)
            {
                // Returning visitor...
            }
            else
            {
                // New visitor - record stats:
                string userAgent = request.ServerVariables["HTTP_USER_AGENT"];
                string ipAddress = request.ServerVariables["HTTP_REMOTE_IP"];
                string time = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss");
                // ...
                // Log visitor stats to database

                TransactionOptions opts = new TransactionOptions();
                opts.IsolationLevel = System.Transactions.IsolationLevel.Serializable;
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, opts))
                {
                    // Update visitor count.
                    // Invalidate cached visitor count.
                }
            }
        }

        #endregion
    }
}

web.config 파일에 다음 줄을 추가 하여이 모듈을 등록하십시오.

<?xml version="1.0"?>
<configuration>
    ...
    <system.web>
        ...
        <httpModules>
          <add name="StatsCounter" type="<ApplicationAssembly>.StatsCounter" />
        </httpModules>
    </system.web>
</configuration>

(웹 애플리케이션 프로젝트의 이름으로 바꾸거나 웹 사이트 프로젝트를 사용하는 경우 제거하십시오.

바라건대, 이것은 실험을 시작하기에 충분할 것입니다. 다른 사람들이 지적했듯이 실제 사이트의 경우 Google (또는 다른) 분석 솔루션을 사용하는 것이 훨씬 좋습니다.

사용 Google 웹 로그 분석. a) 휠이 원하는 것을하지 않거나 b) 휠이 어떻게 작동하는지 알아 내려고하지 않는 한 바퀴를 재발 명하려고하지 마십시오.

이미 사용 가능한 트래픽 분석을 사용하겠다는 두 번째 Gareth의 제안 만 할 수 있습니다. 웹 사이트 트래픽에 Google 데이터를 제공한다는 아이디어가 마음에 들지 않으면 로그 파일을 다운로드하여 많은 것 중 하나로 분석 할 수도 있습니다. 웹 서버 로그 파일 분석 도구 사용 가능.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top