Reading the web.config file from Global.asax

心不动则不痛 提交于 2020-01-07 04:22:09

问题


I have start up code in my Web API project that attempts to read values from the web.config file which is published inside the bin directory by default. Because the application initialization point is Global.asax, there is no web.config at this level so I need to figure out how to reference it down in the bin folder.

Here is the root of my IIS directory:

Anytime I try to read values from the web.config file using ConfigurationManager.AppSettings they come back null. It's only when I move the web.config up out of the bin folder and into the root directory will the values be found.

I tried adding some code that suggested it would force the path to the correct default location (inside the bin folder) before trying to read a value but that doesn't work either:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Fix web.config location
        var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin\\web.config");
        AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path);

        var appId = ConfigurationManager.AppSettings["ApplicationId"];
    }
}

Is there a way to force the path to the web.config living inside the bin folder?


回答1:


Firstly, I am not getting why are you keeping your web.config file in bin folder. Default path of web.config file is always the same folder as global.asax i.e. the root directory of the application. I have been working in ASP.NET, ASP.NET WebAPI and ASP.NET MVC applications and all of them keep web.config in same folder as Global.asax.

Is there anything that you will lose if you move your web.config file from bin directory to the same as global.asax?

Additionally, if it is the connection string that you want to read (as I get from your previous question) you can do below and put your connectionSettings in this web.config of bin directory.

<connectionStrings configSource="bin\connection.config"/>

More details regarding configuration files you can find in this article.



来源:https://stackoverflow.com/questions/29856864/reading-the-web-config-file-from-global-asax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!