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.
-
Notice that the answers below (as of the time of this comment) ignore huge problems: you can add the web.config file as any other file, but it won't affect the runtime, it won't have transformations, and so on, it will only be a static text file.Camilo Terevinto– Camilo Terevinto2020-09-03 19:58:19 +00:00Commented Sep 3, 2020 at 19:58
3 Answers
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.
e.g. 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.
1 Comment
System.Web.Configuration to Microsoft.Extensions.Configuration, and the difference to your statement is huge. web.config is the one and only option, appsettings.json is one of a limitless amount of options (including files, DBs, environment variables, HTTP calls and whatever you want). Also, injecting IConfiguration is a bad practiceAll 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/
Comments
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.