Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
234 views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...