John John
John John

Reputation: 1

Best Way to store configuration setting inside my asp.net mvc application

I am working on a asp.net mvc web application that perform some API calls to other web applications. but currently I am storing the API username, API password and API URL inside my code. As follow:-

using (var client = new WebClient())
                {
                    //  client.Headers[HttpRequestHeader.Accept] = "AddAsset";
                    var query = HttpUtility.ParseQueryString(string.Empty);
                    foreach (string key in formValues)
                    {
                        query[key] = this.Request.Form[key];
                    }

                    query["username"] = "testuser";
                    query["password"] = "……";
                    query["assetType"] = "Rack";
                    query["operation"] = "AddAsset";
var url = new UriBuilder("http://win-spdev:8400/servlets/AssetServlet");
                    url.Query = query.ToString();
                    try
                    {

But storing these setting inside my code will not be flexible in case I need to change the API call settings, and it is not secure. So what is the best way to store these setting . I was thinking to create two database tables one for storing the URL(and there might be multiple URLs sin the future). And another table to store the username and password. So is creating database tables the right way to store these settings.

Upvotes: 21

Views: 20028

Answers (1)

Meryovi
Meryovi

Reputation: 6231

2022 UPDATE: Now in .NET Core you should use the new Configuration API (appSettings.json or other providers / IConfiguration class injected into your classes/controllers), but the same principles apply. Read more about .NET Core configuration here.


You should use the Web.Config file (Configuration API) to store these settings. This way you will be able to update settings without having to recompile your entire application every time. That's the most standard way to store settings in a Web (MVC or WebForms) application, and gives you the possibility to encrypt sensitive settings transparently to your application.

You can access stored settings using the WebConfigurationManager class. Here you can find some examples of how to use it.

Code sample:

Web.config appSettings:

<appSettings>
    <add key="ApiUserName" value="MySampleUsername" />
</appSettings>

C# Code:

string userName = System.Web.Configuration.WebConfigurationManager.AppSettings["ApiUserName"];

Upvotes: 40

Related Questions