asp.net-core - 我需要从 web.Config appSettings 访问值
问题描述
我需要从我的 cshtml 文件中访问 web.config appSettings 中的值
这是我在cshtml文件中的代码:
<body>
<div>
@RenderBody()
<footer>
<p @System.Configuration.ConfigurationManager.AppSettings["myKey"]</p>
</footer>
</div>
...
</body>
这是我来自 web.config 的代码
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="myKey" value="MyValue"/>
</appSettings>
</configuration>
提前致谢
解决方案
首先,System.Configuration.ConfigurationManager用于.net framework而不是.net core。在.net core中,我们通常在appsettings.json中配置。可以参考官方链接。这里有一个demo:
启动.cs:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton<IConfiguration>(Configuration);
}
appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "data source=exmaple;initial catalog=example;persist security info=True;user id=example;password=example"
},
"myKey": "myValue"
}
测试控制器:
public class TestController : Controller
{
IConfiguration _iconfiguration;
public TestController(IConfiguration iconfiguration)
{
_iconfiguration = iconfiguration;
}
public IActionResult TestData() {
ViewBag.Data = _iconfiguration.GetSection("myKey").Value;
return View();
}
}
测试数据.cshtml:
<p> @ViewBag.data</p>
推荐阅读
- dll - 运行共享对象文件版本不匹配的 ELF 文件
- ios - 防止在 Swift 中自动更正单词
- javascript - 给定 GOGS 和目标 ROI 百分比,确定售价的最有效方法是什么?
- keras - 训练 AI 模型需要很长时间
- python - 导入模块适用于 Shell,但不适用于解释器
- java - 交换输入和打印输出作为列
- excel - Excel VBA - 通过代码名称间接引用工作表
- javascript - React - 如何跟踪用户在页面上的当前位置?
- sql - Presto SQL 中 JOIN 表达式的区别
- android - 使用 recyclerview 从 Firebase 查询数据未显示结果