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)
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)
在 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 文件都可以访问的全局变量
归档时间: |
|
查看次数: |
9250 次 |
最近记录: |