Last Updated: February 25, 2016
·
17.05K
· artfulhacker

How to get HttpContextBase from HttpContext.Current in the Global.asax?

In order to implement server-side google analytics tracking into our API for request monitoring we decided to give this library a try:

https://github.com/maartenba/GoogleAnalyticsTracker

In order to get this example below to work inside the Global.asax file

Tracker tracker = new Tracker("UA-XXXXXX-XX", "www.example.org");
tracker.TrackPageView(HttpContext, "My API - Create");

I needed to somehow cast HttpContext.Current into the abstract class HttpContextBase.

Turns out it is as simple as:

new HttpContextWrapper(HttpContext.Current)

so the example becomes:

Tracker tracker = new Tracker("UA-XXXXXX-XX", "www.example.org");
tracker.TrackPageView(new HttpContextWrapper(HttpContext.Current), "My API - Create");