Managing Many Variations of Third Party APIs in ASP.NET

I have a site that uses both Google Analytics and Google Maps. Both of these services have API keys that need to be managed in our site code. For Google Analytics, we have two accounts, a real account and a staging account to check the tracking before lunch. For Google Maps, we really need a unique API key for each hostname. We have multiple staging domains and local hostnames, so our map code has quite a few switches for API keys.

Right now I'm managing my keys in C # code for the respective pages using the switch to Request.Url.Host

:

// for analytics in file1
switch (Request.Url.Host) {
  case "staging": ltlUACode.Text = "stageKey"; break;
  case "client.stage.com": ltlUACode.Text = "stageKey"; break;
  case "www.livesite.com": ltlUACode.Text = "liveKey"; break;
  case "livesite.com": ltlUACode.Text = "liveKey"; break;
}

// for maps in file2
switch(Request.Url.Host) {
  case "staging": GoogleMapsKey = "uniqueKey1"; break;
  case "client.stage.com": GoogleMapsKey = "uniqueKey2"; break;
  case "www.livesite.com": GoogleMapsKey = "uniqueKey3"; break;
  // etc
}

      

I would like to know what is the best way to keep track of all these keys. I considered two possible things that might work:

  • Using app settings in mine web.config

    : One problem here is that card keys change frequently based on hostnames (i.e. many options for a card key would be a management nightmare).
  • Having a C # class to handle all these keys based on the hostname: I could write a static class that has properties for the analytics key and the map key, and based on that Request.Url.Host

    I could set the properties appropriately. This method is essentially my switch method, wrapped in a helper class.
+2


a source to share


2 answers


Do both:

Since they are not code, store Domain => ApiKey pairs in your web config. For large blocks of similar web.config settings, it is useful to create custom sections and handlers . The bonus of the extra work here is that you can extend the functionality of the custom section handlers to return the correct values ​​based on the environment.



Create one type of custom section, then add one section (of this type) for each api key (maps, analytics, etc.).

0


a source


I usually split them into my own files and then deploy different config files based on their location.

web.config

   <appSettings configSource="Host1.config">
        </appSettings>

      



FROM#

System.Configuration.ConfigurationManager.AppSettings(fieldname)

      

0


a source







All Articles