Access key value from Web.config in Razor View-MVC

2019-01-29 19:52发布

问题:

How do I access a key value from web.config in my Razor view.

This is in my web.config in the Web Project root level.

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

I want to have to use the key in my Razor view.

Thank you.

回答1:

@System.Configuration.ConfigurationManager.AppSettings["myKey"]


回答2:

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.



回答3:

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" )">    

}