Skip to main content
Source Link
Cagri Tacyildiz
  • 17.7k
  • 6
  • 38
  • 61

Get Value from appsetting.json in class

I have some appsetting.json below

{
  "MyConfig": {
    "FolderAnnouncement": "Duyuru\\",
    "BaseMediaUrl": "D:\\YoungTalent\\YTPanel\\YTPanel\\wwwroot\\images\\"
  },
  "ConnectionStrings": {
    "MySqlCon": "Server=localhost;Database=kariyer_portal;Uid=root;Pwd=1234;",
    "MsSqlCon": "Server=localhost\\SQLEXPRESS;Database=kariyer_portal;Trusted_Connection=True;ConnectRetryCount=0"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

And I have one class MyConfig.

namespace YTPanel.Models.Model
{
    public interface ITest { string GetFolders(string param); }
    public class MyConfig: ITest
    {
        public MyConfig(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        private readonly IConfiguration Configuration;


        public string BaseMediaUrl { get; set; }
        public string FolderAnnouncement { get; set; }

        public string GetFolders(string param)
        {
           
            string here = Configuration["MyConfig:" + param];
            return here; 
        }
    }   
}

I want to call this class from another class

MyConfig conf;
  private  string SaveAnnouncement(IFormFile file=null,string base64=null)
        {
            string path = conf.GetFolders("FolderAnnouncement");
            string imageUrl = Guid.NewGuid().ToString();
            var mediaPath = conf.GetFolders("BaseMediaUrl");
            string extension = Path.GetExtension(file.FileName);
            var imagePath = mediaPath + path + imageUrl+extension;
            if (!string.IsNullOrEmpty(base64))
            {
                byte[] bytes = Convert.FromBase64String(base64);
                File.WriteAllBytes(imagePath, bytes);  
            }
            else
            {
                using (var fileStream = new FileStream(imagePath, FileMode.Create))
                {
                    file.CopyToAsync(fileStream);
                }
            }
            return  imageUrl+extension;

        }

I added below to ConfigureServices in Startup.

services.AddSingleton<ITest, MyConfig>();

I can't reach the data . How can I solve this problem. I want to reacj appsetting json in one class and I use this class iin any classes I want.

Thanks in advance