[英]ASP.Net Core: passing configuration values to JavaScript client code
I want to pass configuration values from appsettings.json
in ASP.Net Core / 5.0 to a client-side plain JavaScript code;我想将 ASP.Net Core / 5.0 中appsettings.json
中的配置值传递给客户端纯 JavaScript 代码; the parameters will not be changed after setup.设置后参数不会改变。 What is the easiest way to do it?最简单的方法是什么?
You can:你可以:
1 - expose a controller action to fetch configuration and call the backend from JS. 1 - 公开一个 controller 操作以获取配置并从 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. 2 - 将 vales 直接写入 HTML 页面。
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索引.cshtml
@model MyApp.Controllers.HomeIndexModel;
<script type="text/javascript">
window['portalData'] = @Json.Serialize(Model);
</script>
<app-root></app-root>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.