Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store and Retrieve values from web.config

Tags:

I built a small website and there will be only one admin, so in the admin panel I am asking for a password with a value that I do not retrieve from a database, I just hard coded it in the function in code behind, I know this is wrong though I don't know why.

So is hard coding it in web.config the right thing to do? and how?

like image 563
Maen Avatar asked Apr 24 '09 07:04

Maen


People also ask

Why can't I change the value of a value in web config?

The web.config is not designed for that, if you're going to be changing a value constantly, put it in a static helper class. Ryan Farley has a great post about this in his blog, including all the reasons why not to write back into web.config files: Writing to Your .NET Application's Config File CD..

How can I store arbitrary data in web config?

You can store arbitrary data in web.config in the appSettings element: <configuration> <appSettings> <add key="FirstAlias" value="FirstProvider" /> <add key="SecondAlias" value="SecondProvider" /> </appSettings> </configuration>

What is the difference between web config file and appsettings file?

But Web.config file is in XML format and "appsettings.json" file is JSON format. We store the connection strings, keys, and value pairs mostly in "appsettings.json" file.

How to retrieve a value for a specified key from a configuration?

To retrieve a value for a specified key from the <appSettings> section of the configuration file, use the Get method of the AppSettings property of the ConfigurationManager class. The ConfigurationManager class is in the System.Configuration namespace.


Video Answer


2 Answers

As far as it being wrong... the problem is that if you ever need to change it, and it's hardcoded in your codebehind, you need to recompile,republish, re-deploy your website, whereas a change to the web.config can be done without doing this.

You could put it in an AppSetting in the web.config like so.

<appSettings>    <add key="AdminPassword" value="ASDF1234" /> </appSettings> 

and use this code to retrieve it

System.Configuration.ConfigurationManager.AppSettings["AdminPassword"].ToString() 

Though I'd have a look at this.

http://aspnet.4guysfromrolla.com/articles/021506-1.aspx

It covers encrypting sections of your web.config

like image 140
Eoin Campbell Avatar answered Oct 18 '22 23:10

Eoin Campbell


Nothing wrong with Eoin's suggestion for tiny projects but if your project may someday need more than 1 admin and different types of users roles. I would take the hit and setup ASP membership.

http://msdn.microsoft.com/en-us/library/ms998347.aspx

You can use integrate it into windows or use a database and it's not too hard to setup. Especially if you use the built in config tool in IIS.

like image 28
Chad Grant Avatar answered Oct 19 '22 01:10

Chad Grant