.NET System Configuration converting to .NET Core Microsoft Configuration

Viewed 44

Tryin to convert .NET Project to a Microservice Project using .NET Core. Since I've a limited knowledge of .NET core, I'm having a hard time figuring out what changes are to be made to make it working. Understand that web.config file configuration can be replaced by appsettings.json but apart from that what else configuration has to be made. I'd appreciate it very much if can help to convert the following .NET Configuration to .NET Core configuration. Thanks.

Here the problem is using HostingEnvironement.MapPath. On using Path.Combine it seems working but again no changes is done in the Startup.cs.

Class A
{
public static IXPathNavigable GetContent()
{
   string getAbsolutePath = 
   HostingEnvironment.MapPath(AConfiguration.GetSection().Settings.folderPath + filename);
}

ASP.NET way of configuration.

 using System.Configuration;

 public class AConfig: ConfigurationSection
    {
        public const string Name = "customConfiguration";
        public static AConfig GetSection()
        {
            return ConfigManager.GetSection(DefaultSectionName) as AConfig;
        }

        [ConfigurationProperty("settings")]
        public SettingsElement Settings
        {
            get
            {
                return (SettingsElement)base["settings"];
            }
        }
    }

 public class SettingsElement : ConfigurationElement
    {
        public SettingsElement()
        { }

        [ConfigurationProperty("folderPath ", IsRequired = true)]
        public string FolderPath
        {
            get { return (string)base["FolderPath"];}
            set { base["FolderPath"] = value; }
        }

Web.Config File.

 <AConfig>
    <settings
    FolderPath="~/Path/" 
      />
  </AConfig>

What I tried is updating the JSON and ClassA.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "AConfig": {
    "FolderPath": "~/Path/"
  }
}

// In ClassA

using Microsoft.Extensions.Configuration;
Class A
{
public static IXPathNavigable GetContent()
{
   string getAbsolutePath = 
   Path.Combine(new 
ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("AConfig")["FolderPath"] + filename);
}
1 Answers

You could access the WebRootPath and ContentRootPath with IWebHostEnvironment

inject it into the dependent class like:

public class HomeController : Controller {
    private IWebHostEnvironment _hostEnvironment;

    public HomeController(IWebHostEnvironment environment) {
        _hostEnvironment = environment;
    }

    [HttpGet]
    public IActionResult index() {
        string path = Path.Combine(_hostEnvironment.WebRootPath, "filename");
        return View();
    }
}
Related