Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 582
Val K Avatar asked Nov 18 '25 23:11

Val K


1 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.

like image 151
Dezzamondo Avatar answered Nov 20 '25 12:11

Dezzamondo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!