Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tracking ASP.NET Web API with google analytics

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

like image 295
developer82 Avatar asked Jan 28 '14 05:01

developer82


2 Answers

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

like image 104
Aristos Avatar answered Oct 23 '22 15:10

Aristos


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

like image 2
Paresh Avatar answered Oct 23 '22 14:10

Paresh