.NET 6 MVC read config from Model

Eligio Morgado 61 Reputation points
2022-02-13T19:45:09.067+00:00

Hello.

I'm trying to find the right way to read config in appsettings.json from Model.

I have a BaseModel with a common method for making GET request to an Api. All models inherit from BaseModel, so, on a specific Model, I can execute the base method for GET.
In appstettings.json I have an entry "ApiURL". I want from BaseModel to read that config key.

I have tried to add a constructor parameter "IConfiguration configuration" in the base class, but the problem is that I get an error saying that you need an empty constructor. But if I create an empty constructor, configuration is never initialized.

¿How do you read appsettings.json from a model?

Thanks

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,505 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,829 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,146 Reputation points Microsoft Vendor
    2022-02-14T07:01:05.967+00:00

    Hi @Eligio Morgado ,

    In the BaseModel constructor method, you can refer the following code to create a configuration instance:

    public class BaseModel  
    {  
        private readonly IConfiguration _config;  
        public BaseModel()  
        {  
            _config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();   
        }  
        public string Name { get; set; }  
    
        public string GetConnection()  
        {  
            return _config.GetConnectionString("DefaultConnection");  
        }  
    }  
    

    Then, the result is like this:

    174006-image.png


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 63,916 Reputation points
    2022-02-13T20:21:51.683+00:00

    This is a poor design. You should not have models (or actions) read a configuration file. Your model really should only have methods that access model data. An api call should be done outside the model with an adapter.

    The adapter should be created at startup and injected.

    Please study standard design patterns


  2. Karen Payne MVP 35,401 Reputation points
    2022-02-13T21:51:41.02+00:00

    See if this will work for you. C:\OED needs to be replaced with were the file you want to read resides. And as mentioned, placing this in the model is not a good idea.

    Class

    public class Example
    {
        public string SomeProperty { get; set; }
    }
    

    Read json

    public class Helper
    {
    
        public static string ConfigurationFileName { get; set; } = "appsettings.json";
        public static Example Example()
        {
            var config = InitMainConfiguration();
            return config.GetSection("Section1").Get<Example>();
        }
        private static IConfigurationRoot InitMainConfiguration()
        {
    
            var builder = new ConfigurationBuilder()
                // change the path to where ever the json file resides
                .SetBasePath("C:\\OED")
                .AddJsonFile(ConfigurationFileName);
            return builder.Build();
        }
    }
    

    Model

    public class SomeModel
    {
        public int  Id { get; set; }
        public void DoSomething()
        {
            Example result = Helper.Example();
            Debug.WriteLine(result.SomeProperty);
        }
    }
    

    Execution

    SomeModel someModel = new SomeModel();
    someModel.DoSomething();
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.