【问题标题】:I need to access value from web.Config appSettings我需要从 web.Config appSettings 访问值
【发布时间】:2021-03-01 16:19:35
【问题描述】:

我需要从我的 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-core configuration web-config settings


【解决方案1】:

首先,System.Configuration.ConfigurationManager用在.net framework而不是.net core中。在.net core中,我们通常在appsettings.json中配置。可以参考official link。这里有一个demo:

Startup.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();
        }
    }

TestData.cshtml:

<p> @ViewBag.data</p>

结果:

【讨论】:

    猜你喜欢
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多