首页 > 解决方案 > 我需要从 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>

提前致谢

标签: asp.net-core.net-coreconfigurationweb-configsettings

解决方案


首先,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>

结果: 在此处输入图像描述


推荐阅读