在Razor View-MVC3 ASP.NET中访问web.config的键值

如何在Razor视图中从web.config访问键值?

这是我的web.config中的Web项目根级别。

 <appSettings>
<add key="myKey" value="MyValue"/>
</appSettings>

我想在我的Razor视图中使用密钥。

谢谢。

139979 次浏览
@System.Configuration.ConfigurationManager.AppSettings["myKey"]

The preferred method is actually:

@System.Web.Configuration.WebConfigurationManager.AppSettings["myKey"]

It also doesn't need a reference to the ConfigurationManager assembly, it's already in System.Web.

Here's a real world example with the use of non-minified versus minified assets in your layout.

Web.Config

<appSettings>


<add key="Environment" value="Dev" />


</appSettings>

Razor Template - use that var above like this:

@if (System.Configuration.ConfigurationManager.AppSettings["Environment"] == "Dev")
{
<link type="text/css" rel="stylesheet" href="@Url.Content("~/Content/styles/theme.css" )">


}else{


<link type="text/css" rel="stylesheet" href="@Url.Content("~/Content/styles/blue_theme.min.css" )">


}

FOR MVC

-- WEB.CONFIG CODE IN APP SETTING -- <add key="PhaseLevel" value="1" />

-- ON VIEWS suppose you want to show or hide something based on web.config Value--

-- WRITE THIS ON TOP OF YOUR PAGE-- @{ var phase = System.Configuration.ConfigurationManager.AppSettings["PhaseLevel"].ToString(); }

-- USE ABOVE VALUE WHERE YOU WANT TO SHOW OR HIDE.

@if (phase != "1") { @Html.Partial("~/Views/Shared/_LeftSideBarPartial.cshtml") }