Skip to content

How to store the URL for an API endpoint in App.config

Recently I’ve been working on a .NET console app that occasionally has to call two RESTful APIs. Per best practices, I did not want to hardcode the base URLs for these APIs in code because then I would have to redeploy the application if they were to change. Using App.config is a good solution for this, so here’s how to store the URL for an API endpoint in App.config.

First of all, you could store these URLs either in the <appSettings> section or the <connectionStrings> section of App.config, but I prefer to only use the <connectionStrings> section for database connection strings.

If you feel the same way, go to your App.config and check if you have an <appSettings> section within <configuration>. If you don’t, create it. Then for each URL you’d like to store, create an entry with the following attributes: <add key="[unique endpoint name]" value="[endpoint URL]" />. Here’s an example:

<?xml version="1.0" encoding="utf-8"?>
    <add key="nbaStatsUrl" value="" />
    <add key="nflStatsUrl" value="" />

Once you’ve added entries to the <appSettings> section, simply use the .NET ConfigurationManager to access their values in code by their key:

using System.Configuration;
string nbaStatsUrl = ConfigurationManager.AppSettings["nbaStatsUrl"];
string nflStatsUrl = ConfigurationManager.AppSettings["nflStatsUrl"];

Super simple, and no third-party libraries required.

Published inTips & Tricks

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *