How to read web.config file in .Net Core app

后端 未结 6 1461
逝去的感伤
逝去的感伤 2020-12-01 15:51

I have created a .Net Core API and I referenced a .Net framework application to it. The referenced Application connects to a data base and its connection string is stored in

6条回答
  •  情深已故
    2020-12-01 16:48

    For .NET Core apps, the best way is to use the Configuration API. This is a very flexible way and, thanks to providers pattern, it allows to use a different sources, not only the most common appsettings.json file (that by the way just a JSON file and could be named in a random way):

    • File formats (INI, JSON, and XML)
    • Command-line arguments
    • Environment variables
    • In-memory .NET objects
    • An encrypted user store Azure Key Vault
    • Custom providers, which you install or create

    Now about ConfigurationManager . At first, the .NET Core forced to forget about this class - it was not implemented and supported and the idea was to fully replace it by providing new Configuration API.

    Moreover, the reality is that ASP.NET Core apps aren't hosted via IIS anymore (IIS works mainly as a reverse proxy now), and so the web.config is not so useful anymore (unless rare cases when you still need to define parameters specific to IIS configuration).

    Though, after the .NET Standard 2.0 was provided, this System.Configuration.ConfigurationManager nuget package is available and brings back the ConfigurationManager class. It became possible due to new compatibility shim implemented in new .NET Core 2.0.

    Regarding your case, it is difficult to say why you have 'null' as it not enough information:

    • it may be a wrong section in web.config
    • web.config may not be copied into your output/publishing folder

提交回复
热议问题