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?
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..
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>
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With