Patrick
Patrick

Reputation: 2781

Google Analytics based on Microsoft.AspNet.Identity roles

I am trying to find a way to register all the traffic of a website with Google Analytics, spliting the reporting based on the Microsoft.AspNet.Identity role.

I did not found anything that allows to do it.

Something like:

if(User.IsInRole("public")) 
{
  <script>
    (function (i, s, o, g, r, a, m) {
        i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
            (i[r].q = i[r].q || []).push(arguments)
        }, i[r].l = 1 * new Date(); a = s.createElement(o),
        m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
    })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

    ga('create', 'PUBLIC', 'auto');
    ga('send', 'pageview');

  </script>
}
else if (User.IsInRole("private")) 
{
   <script>
    (function (i, s, o, g, r, a, m) {
        i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
            (i[r].q = i[r].q || []).push(arguments)
        }, i[r].l = 1 * new Date(); a = s.createElement(o),
        m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
    })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

    ga('create', 'PRIVATE', 'auto');
    ga('send', 'pageview');

  </script>
}

Upvotes: 5

Views: 133

Answers (2)

Patrick
Patrick

Reputation: 2781

I have been testing for a few days now and I found a great way to have 2 different properties in the same account:

@if (Model.IsUserInternal == true)
{
<script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-XXXXXXXXX-2', 'auto');
    ga('send', 'pageview');
</script>    
}
else
{
<script>
    (function(i, s, o, g, r, a, m) {
    i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function() {
    (i[r].q = i[r].q || []).push(arguments)
    }, i[r].l = 1 * new Date(); a = s.createElement(o),
    m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
    })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

    ga('create', 'UA-XXXXXXXXX-1', 'auto');
    ga('send', 'pageview');
</script>
}

Where XXXXXXXXX is the same.

Upvotes: 0

Christian Gollhardt
Christian Gollhardt

Reputation: 17004

You are looking for the User ID feature. Here is a Tutorial.

You need to setup the feature. Then you can start tracking like this:

ga('create', 'UA-XXXXXX-Y', {'userId': customUserId});

Anonymous Users you can detect by

User.Identity.IsAuthenticated

You want to send a userid that you do not have like 0 for anonymous users.

Upvotes: 2

Related Questions