0

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?

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.