Configure Mobile.BuildTools in .NET MAUI to keep your secrets safe

I had some issues at first with compiling after doing my first migration from Xamarin to .NET MAUI with Mobile.BuildTools but I went back to some of mother other apps and found my old solution to a new problem.

The nuget works great in MAUI and I am more comfortable with it than some of the newer methods to keep secrets out of your source. So here is a quick overview of what it takes to configure it and get it working in your .NET MAUI or Xamarin app.

Understanding the configuration file for the nuget is key. There are some subtle things in the config that need to be set properly in order for it to work right. Here is an example config for your to look at.



So in the JSON file the basics I commented on are to set the project name, class name (I made a folder called Helpers and put “Helpers” there in that spot), and root namespace of the app. Then you can enter in your secret NAME/TYPE pairs, so it can be a string or whatever. Generally, it will be strings for your secrets but what you name them here is a reference in the actual secrets file itself.

The secrets file should be named after the class name you defined in your JSON file. So if you called it AppSecrets then you would name your secrets file “appsecrets.json.” Pretty straightforward forward but it can lead to problems later on that are hard to figure out without some debugging. In your secrets file you use the NAMES defined in your config as KEY/VALUE pairs in it and it is formatted in ordinary JSON format like below.



Now in code, you refer to your secrets by the Class Name then a dot then the Secret Name you input into your config. So you would refer to ApiKey as “AppSecrets.ApiKey.” So in your code, you can refer to it like this, “var myapikey = AppSecrets.ApiKey.”

The rest can be ignored if you are not using the full capabilities of Mobile.BuildTools.

If you run into a compile error complaining about build tools that refer to some weird message about build properties, here is what you need.



Name it like in the gist and then place that file with your .sln file in the root of your project so MS Build can find it. Then the error should go away, I don’t remember the exact specifics of it but the file remedies that.