k1dl3r
k1dl3r

Reputation: 103

.Net Core 2.1 - Read appsettings.json in javascript file

I have a Web application in .net Core 2.1 using signalR. I need to pass HubUrl into custom javascript file. Is that possible in .net Core?

Sample of js code:

const connection = new signalR.HubConnectionBuilder()
.withUrl('http://localhost:5000/hub') //Here I need to read appSettings.json to get value from there
.configureLogging(signalR.LogLevel.Information)
.build();

Upvotes: 7

Views: 18220

Answers (5)

tejas n
tejas n

Reputation: 728

In appsettings.json

"ApiUrls": {
    "commonUrl": "https://localhost:44348/api/"    
  }

In _Layout.cshtml

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<script>      
        const commonUrl = @Json.Serialize(@Configuration.GetSection("ApiUrls").GetSection("commonUrl").Value)
</script>

now this will be like a global variable accessible to all js files

Upvotes: 9

Kurkula
Kurkula

Reputation: 6762

respecting "Maxemelian"'s answer, extending answer by adding validation cases to check

  1. If section name is null
  2. Ignoring secret
private readonly IConfiguration configuration;

public MyController(IConfiguration configuration){
     this.configuration = configuration;
}

[HttpGet("[action]")]
public ActionResult GetConfigurationValue(string sectionName, string paramName)
{
    if (paramName.ToLower().Contains("secret")) {
        return null;
    }

    var parameterValue = (!string.IsNullOrEmpty(sectionName)) ? config[$"{sectionName}:{paramName}"] : config[$"{paramName}"];
    return Json(new { parameter = parameterValue });
}

Upvotes: 0

Mark Z.
Mark Z.

Reputation: 2447

In an SPA with webpack, you can just import the appsettings.json and make it available via a convenience class that you import;

e.g.

appsettings.js:

appsettingsjson = process.env.NODE_ENV === 'development'
    ? require('./appsettings.Development.json')
    : require('./appsettings.json');

class AppConfig {

    constructor() {
    }

    static Settings() {
        return appsettingsjson;
    }
}

module.exports = AppConfig;

Then wherever you need it, just import and use. e.g.:

const AppConfig = require("./appsettings");
console.log(AppConfig.Settings().YourSection.YourParameter)

Upvotes: 1

poke
poke

Reputation: 388023

A very safe yet flexible way to do this is to expose the URL inside a <script> block in a view. That way, you are not exposing application configuration (which access you will have to protect very well) but instead just explicitly expose a single secure value.

It also has the added benefit that you do not need to make a request to an endpoint (which address you actually also need to know in your script) but have the value instantly there when you need it.

To do that, you can simply render a <script> tag that defines the value globally. For example, you could have the following in your layout:

<script>
window._signalRAddress = @Json.Serialize(ViewData["SignalRAddress"]);
</script>
<script src="~/your-custom-script.js"></script>

And then you just use window._signalRAddress inside of your script.

Upvotes: 3

maximelian1986
maximelian1986

Reputation: 2462

appsettings.json located on server. So you need to add end-point to controller that returns needed value.

Controller:

public class MyController:Controller{
    private readonly IConfiguration configuration;

    public MyController(IConfiguration configuration){
         this.configuration = configuration;
    }

    [HTTPGet]
    public ActionResult GetConfigurationValue(string sectionName, string paramName){
        var parameterValue= configuration[$"{sectionName}:{paramName}"];
        return Json(new { parameter= parameterValue});
    }
}

Client side:

$.ajax({
    type:"GET",
    url: "/MyController/GetConfigurationValue"
    data:{
        sectionName = "MySection",
        paramName = "MyParameter"
    }
}).done(
    function(parameterValue){
        //do what you need
});

In appsettings.json:

{
    "MySection":{
        "MyParameter":"value that I want to get"
    }
}

Upvotes: 10

Related Questions