How do I add custom application settings?
There are many ways to supply custom application settings e.g. connection strings to your application, and the official ASP .NET documentation explains in great detail the various options you have available.
Configuration of the Server
In this recipe, we show how to add configuration using an appsettings.json
configuration file.
Never store secrets in plain text files such as
appsettings.json
- our recommendation is to use it for non-secret configuration data that is shared across your development team; see here for more guidance.
- In the Server folder, add a file
appsettings.json
. It does not need to be added to the project file. - Add the following content to it:
{ "MyKey": "My appsettings.json Value" }
- In
Server.fs
, ensure that your API builder functions take in anHTTPContext
as an argument and change the construction of your Fable Remoting endpoint to supply one:++open Microsoft.AspNetCore.Http --let todosApi = { ++let todosApi (context: HttpContext) = { ... -- |> Remoting.fromValue todosApi ++ |> Remoting.fromContext todosApi
- Use the
context
to get a handle to theIConfiguration
object, which allows you to access settings regardless of what infrastructure you are using to store them e.g.appsettings.json
, environment variables etc.++open Giraffe ++open Microsoft.Extensions.Configuration let todosApi (context: HttpContext) = ++ let cfg = context.GetService<IConfiguration>() ++ let value = cfg["MyKey"] // "My appsettings.json Value"
Note that the
todosApi
function will be called on every single ASP .NET request. It is safe to "capture" thecfg
value and use it across multiple API methods.
Publishing settings files
Be aware that appsettings.json
files will be included in your bundle by default. However, depending on your application, it can be overridden by e.g. environment variables.
Working with User Secrets
User Secrets are an alternative way of storing secrets which, although still stored in plain text files, are not stored in your repository folder and therefore less at risk to accidentally committing into source control. However, Saturn currently disables User Secrets as part of its startup routine, and you must manually turn them back on:
++type DummyType() = class end
let app = application {
++ host_config (fun hostBuilder ->
++ hostBuilder.ConfigureAppConfiguration(fun _ configBuilder ->
++ configBuilder.AddUserSecrets<DummyType>()
++ |> ignore
++ )
++ )
}
You can then access the IConfiguration
as before, and user secrets values will be accessible.
Configuration of the client
Configuration of the client can be done in many ways, but generally a simple strategy is to have an API endpoint which is called on startup that provides any settings required by the client.