Tracking ASP.NET Web API with google analytics

匆匆过客 提交于 2021-01-27 06:27:12

问题


I'm developing an API for my website that users can access and use own their own websites/apps.

I would like to keep usage statistics for the use of the different API calls I allow, and would like to use Google Analytics like I do for my website. Is it possible to track with Google Analytics on server side code? or specifically web api?

Thanks


回答1:


Google analytics have give the mobile code to track the statistics from server side. You may use that code to archive your goal.

What this actually do is to make a web request from server side to google with the informations you give him. The call is done to a gif image with url parameters as:

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);

And the request is like:

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);
        }
    }
}

You can get the full example from google site and with little change on original code, to make it work for you.

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

This is a general idea, you have some work to do, but all the code you need is on that file : http://dl.google.com/gaformobileapps/googleanalyticsformobile.zip




回答2:


You could use Google Analytics Tracker NuGet package. Here is the link.. https://github.com/maartenba/GoogleAnalyticsTracker



来源:https://stackoverflow.com/questions/21397907/tracking-asp-net-web-api-with-google-analytics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!