0

I'm trying to get a path url from the following notificatorConfig.json file:

{
  "UserNotificatorConfig": {
    "URL": "http://localhost:8001",
    "BasePath": "/send-message/android"
  }
}

Using a ConfigurationBuilder() as follows:

public async Task Send(string message)
{
    var config = new ConfigurationBuilder()
                           .AddJsonFile("notificatorConfig.json", true)
                           .Build();

    var url = config.GetSection("UserNotificatorConfig:URL").Value;
    var basePath = config.GetSection("UserNotificatorConfig:BasePath").Value;

    await _rest.PostAsync<Notification>(url, basePath, message);
}

Both my json file and the file where my Send() method is located, are in the same folder.

But every time I try to debug this method on unit tests I get null values for both parameters url and basePath.

What am I missing here?

1
  • 1
    Your code looks a bit off to me. Building the configuration is something that's done in startup. Why are you trying to build it in some method during runtime? Commented May 22, 2020 at 23:59

1 Answer 1

1

You need to add SetBasePath(Directory.GetCurrentDirectory()):

var config = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("notificatorConfig.json", true)
    .Build();

And, as @Dennis1679 said, you should build configuration in startup.

Edit:

If this doesn't help, access Value inside Section this way:

var userNotificatorConfig = config.GetSection("UserNotificatorConfig");
var url = userNotificatorConfig.GetValue<string>("URL");
var basePath = userNotificatorConfig.GetValue<string>("BasePath");

Instead of this way:

var url = config.GetSection("UserNotificatorConfig:URL").Value;
var basePath = config.GetSection("UserNotificatorConfig:BasePath").Value;
Sign up to request clarification or add additional context in comments.

4 Comments

No game, when I do this GetCurrentDirectory() returns my tests directory and not the one where my json is located.
According to this: stackoverflow.com/questions/39791634/…. There is a specific issue about using GetCurrentDirectory() on a test project, it is recommended that I keep a copy of my json file in the test project. I see a big issue here as I would have to assure equality in two different json files.
@RogerioSchmitt This might help you: stackoverflow.com/questions/674857/…. I see a big issue here as I would have to assure equality in two different json files. I agree with you, however, it is a valid everyday solution.
@RogerioSchmitt I've added another way of accessing Values in UserNotificatorConfig section, if previous solution doesn't help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.