Adding Google Analytics Tag to .NET 6 SwaggerUI project

I'm working on a .NET 6 API project that uses MVC with Swagger. One requirement was to get the Swagger page into my Google Analytics account.

Steps:

  1. Add wwwroot folder and then a js subdirectory. Visual Studio will automatically make this pretty for you.

2. Go to Startup.cs and add app.UseStaticFiles(); to your Configure method before your app.UseSwagger(); line.

3. Put the second piece of your Google Analytics tag in a file in that js directory. I used analytics.js. IMPORTANT: Remove the surrounding script tag or you will get a syntax error (Uncaught SyntaxError: Unexpected token '<') in your browser console.

4. Update your app.UseSwaggerUI method with two javascript injections:

Publish / reload and data will start showing up in Google Analytics.