简体   繁体   中英

How can I use set Environment Variables in Xamarin.Forms from App Center

I have a Xamarin Forms app which is being built using App Center. The app contains some code that looks like:

var secret= "secretvaluegoeshere";

I then use the secret to communicate with an API. Now I want to extract that secret from code so as not to having it in source control and inject it when building on App Center. Environment Variables seem like they should solve this very problem but the examples in the docs don't mention how they can get into code (only nuget and gradle config). Is there a way to do what I want with Environment Variables or should I be doing this another way?

您可以通过预构建脚本将其注入到项目中(直接在代码中替换一些占位符,创建一些资源文件等),然后在运行时从那里读取它。

So it turns out this is surprisingly easy by following these steps:

Install the Mobile.BuildTools NuGet package in your project.

Add a secrets.json file in the root of your project (this should be excluded from source control using .gitignore).

Add your secret to the secrets.json file, so in my case I'm going to add a SearchApiKey, obviously you can add as many secrets as you want:

{
  "SearchApiKey": "SUPERSECRETGOESHERE"
}

Build your project and this will generate a static class called Secrets with a property SearchApiKey, you can find it under the obj folder if you want to have a look at it.

You can now access this class and it's properties in your code so I just do:

var secret = Secrets.SearchApiKey;

Finally to pass the secret into your build on AppCenter you need to add an Environment Variable that matches the property name prepended with Secret_ so in my case it's name is Secret_SearchApiKey and set it's value.

You can check out the Mobile.BuildTools GitHub repository for more information.

If you don't want to use additional nuget packages, you can follow example posted from the official AppCenter project on GitHub

What you have to do is create a new environment variable on AppCenter with the value you want to set. Then save a file named appcenter-pre-build.sh at the same lever of your .csproj file and create your own code like in the example.

Once you have added the file to your repo, in order to save the detected scripts to the build configuration, you have to hit the “Save” or “Save & Build” button in the build configuration

It worked for me like a charm a momment ago, hope it helps someone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM