使用谷歌分析跟踪ASP.NET Web API

dev*_*r82 4 asp.net google-analytics asp.net-web-api

我正在为我的网站开发一个API,用户可以访问并使用自己的网站/应用程序.

我想保留使用我允许的不同API调用的使用情况统计信息,并希望像我为我的网站一样使用Google Analytics.是否可以使用Google Analytics跟踪服务器端代码?或者特别是web api?

谢谢

Ari*_*tos 6

谷歌分析已经提供移动代码来跟踪服务器端的统计数据.您可以使用该代码存档您的目标.

这实际上做的是从服务器端向谷歌请求你给他的信息.使用url参数对gif图像进行调用:

string utmGifLocation = "http://www.google-analytics.com/__utm.gif";

string utmUrl = utmGifLocation + "?" +
    "utmwv="   + Version +
    "&utmn="   + RandomNumber +
    "&utmhn="  + HttpUtility.UrlEncode(domainName) +
    "&utmr="   + HttpUtility.UrlEncode(documentReferer) +
    "&utmp="   + HttpUtility.UrlEncode(documentPath) +
    "&utmac="  + account +
    "&utmcc=__utma%3D999.999.999.999.999.1%3B" +
    "&utmvid=" + visitorId +
    "&utmip="  + GlobalContext.Request.ServerVariables["REMOTE_ADDR"];

SendRequestToGoogleAnalytics(utmUrl);
Run Code Online (Sandbox Code Playgroud)

请求如下:

private void SendRequestToGoogleAnalytics(string utmUrl)
{
    try
    {
        WebRequest connection = WebRequest.Create(utmUrl);

        ((HttpWebRequest)connection).UserAgent = GlobalContext.Request.UserAgent;
        connection.Headers.Add("Accepts-Language",
            GlobalContext.Request.Headers.Get("Accepts-Language"));

        using (WebResponse resp = connection.GetResponse())
        {
            // Ignore response
        }
    }
    catch (Exception ex)
    {
        if (GlobalContext.Request.QueryString.Get("utmdebug") != null)
        {
            throw new Exception("Error contacting Google Analytics", ex);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以从谷歌网站获得完整的示例,并且对原始代码几乎没有任何更改,以使其适合您.

https://developers.google.com/analytics/devguides/collection/?csw=1

这是一个大致的想法,您还有一些工作要做,但您需要的所有代码都在该文件中:http://dl.google.com/gaformobileapps/googleanalyticsformobile.zip