简体   繁体   中英

Add web.config file to Asp.Net Core project

I am building an Asp.Net Core 3.1 project that will reference some older .Net Framework APIs. The APIs are built to fetch configuration values from the web.config file hosted by the calling application. Up until now all the calling apps were also .Net Framework apps and contained web.config files. The new project is .Net Core. How would I add a web.config file to a .Net Core project so that the API could access it? I tried just adding a web.config to the solution with the right app settings values. Didn't work.

ASP.NET Core replaced the web.config file with appsettings.json instead. If the API that needs to read the config is also the same project, then it should be as easy as adding IConfiguration as a dependency in your API controller constructor and extracting the values directly from it.

eg SomeApiController.cs

public class SomeApiController : Controller
{
    private readonly IConfiguration _config;

    public SomeApiController (IConfiguration configuration)
    {
        _config = configuration;
    }


    public IActionResult SomeEndpoint()
    {
       var connectionString = _config.GetConnectionString("DefaultConnection");

       return connectionString;
    }
}

Alternatively, if you really, REALLY need to have a web.config file instead, then I would suggest using an XML reader to read the file directly. There's a tutorial out there somewhere for it that's several years old now, but I can't quite find it at the moment.

Since your project, meaning the code that you control, will not consume the web.config file, all you have to do is add it and make sure it's copied to the output directory. Here is a post that details the few steps: https://mitchelsellers.com/blog/article/using-a-web-config-file-with-asp-net-core .

If you can also modify these old APIs, then you should try to decouple the dependency on the web.config file so that you don't have to have a separate configuration for those.

All I had to do is to add an app.config file with some keys and install System.Configuration.ConfigurationManager as a NuGet package. Here is the link: https://www.itnota.com/use-system-configuration-configurationmanager-dot-net-core/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM