ASP.NET: Sharing configuration between frontend and backend
Posted: (EET/GMT+2)
Sometimes you want your JavaScript frontend to know about values already defined in your ASP.NET configuration. For example, these might be some API URLs, constant values or option flags, without duplicating them both at the backend and frontend.
A simple and safe way is to expose selected settings through a controller or Razor helper that reads from appsettings.json, and passes them to frontend as a JavaScript object.
Here's an example. First, define some settings in the backend:
// appsettings.json
{
"ApiBaseUrl": "https://api.example.com/",
"FeatureXEnabled": true
}
Then, in the C# code's startup logic, make the configuration working:
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration);
services.AddMvc();
}
public class AppSettings
{
public string ApiBaseUrl { get; set; }
public bool FeatureXEnabled { get; set; }
}
Third, create a simple controller that looks like it points to a JavaScript file,
and this assigns the data to the browser's window object:
// ConfigController.cs
[Route("config.js")]
public class ConfigController : Controller
{
private readonly AppSettings _settings;
public ConfigController(IOptions<AppSettings> settings)
{
_settings = settings.Value;
}
[HttpGet]
public ContentResult Get()
{
string json = JsonConvert.SerializeObject(_settings);
string script = $"window.appConfig = {json};";
return Content(script, "application/javascript");
}
}
Now your frontend can use:
console.log(window.appConfig.ApiBaseUrl);
This keeps configuration in one place (the server) and still lets your frontend read what it needs. Just be sure to only expose non-sensitive values.