Start Debugging
2020-11-13 Updated 2023-11-05 csharpxamarin-forms

How to use appsettings.json with Xamarin.Forms

Learn how to use appsettings.json configuration files with Xamarin.Forms by embedding the file as a resource and building an IConfiguration object.

There are two key differences compared to ASP.NET:

To get started, add an appsettings.json file in your shared project. Make sure you set its Build Action to Embedded Resource. Add some keys + value in the file that we can use for testing. For example:

{
  "ChatHubUrl": "https://signalrchatweb.azurewebsites.net/"
}

Next, we need to get hold of the resource stream.

Stream resourceStream = GetType().GetTypeInfo().Assembly.GetManifestResourceStream("SignalRChat.appsettings.json");

And use it to build an IConfiguration object.

var configuration = new ConfigurationBuilder()
                .AddJsonStream(resourceStream)
                .Build();

Now, in order to pull the configuration values from it, just use it like you would any other dictionary.

configuration["ChatHubUrl"];

Alternatively you can register it into your IoC container as an IConfiguration , inject that into your viewmodels and use it in the same way.

For a complete example you can check out this repository on GitHub: Xamarin Forms – SignalR Chat.

< Back