.Net Core 2.1 - 在 javascript 文件中读取 appsettings.json

k1d*_*l3r 4 javascript signalr asp.net-core-mvc .net-core asp.net-core

我在 .net Core 2.1 中有一个使用 signalR 的 Web 应用程序。我需要将 HubUrl 传递到自定义 javascript 文件中。这在 .net Core 中可能吗?

js代码示例:

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();
Run Code Online (Sandbox Code Playgroud)

max*_*986 8

appsettings.json 位于服务器上。因此,您需要向返回所需值的控制器添加端点。

控制器:

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});
    }
}
Run Code Online (Sandbox Code Playgroud)

客户端:

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

在 appsettings.json 中:

{
    "MySection":{
        "MyParameter":"value that I want to get"
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,此实现非常危险,因为它允许任何人读取 **any** 配置值,包括连接字符串或其他内部值等秘密。如果您希望有一个端点来返回配置值,您应该将其限制为很少的显式值和/或具有非常强大的输入验证以防止人们访问关键信息。 (4认同)

tej*_*s n 5

appsettings.json

"ApiUrls": {
    "commonUrl": "https://localhost:44348/api/"    
  }
Run Code Online (Sandbox Code Playgroud)

_Layout.cshtml

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<script>      
        const commonUrl = @Json.Serialize(@Configuration.GetSection("ApiUrls").GetSection("commonUrl").Value)
</script>
Run Code Online (Sandbox Code Playgroud)

现在这就像一个所有 js 文件都可以访问的全局变量