Reputation: 4727
I want to pass configuration values from appsettings.json
in ASP.Net Core / 5.0 to a client-side plain JavaScript code; the parameters will not be changed after setup. What is the easiest way to do it?
Upvotes: 0
Views: 585
Reputation: 3118
You can:
1 - expose a controller action to fetch configuration and call the backend from JS.
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly IConfiguration _config;
public ValuesController(IConfiguration config)
{
_config = config;
}
[HttpGet("config")]
public ActionResult Get()
{
var data = new
{
SomeValue = _config["SomeValue"]
};
return Ok(data);
}
}
fetch('api/values/config').then(function(response) {
console.log(response);
})
2 - write the vales directly to the HTML page.
public class HomeController : Controller
{
private readonly IConfiguration _config;
public HomeController(IConfiguration config)
{
_config = config;
}
public IActionResult Index()
{
var model = new HomeIndexModel
{
SomeValue = _config["SomeValue"]
};
return View(model);
}
}
Index.cshtml
@model MyApp.Controllers.HomeIndexModel;
<script type="text/javascript">
window['portalData'] = @Json.Serialize(Model);
</script>
<app-root></app-root>
Upvotes: 1