Reading appsetting-test.json file in asp.net core 5 test project

3.9k Views Asked by At

I have a test project with Asp.net core 5 and trying to read the appsetting values.

Created an appsetting.test.json file in the test project with below configuration

{
    "baseUrl": "https://xxxxx.io/",
    "user": {
        "username": "[email protected]",
        "password": "xxxxxxx@1xx7"
    }
}

Created a helper class to read the json file

  public interface IAppSettingConfiguration
    {
        public static IConfiguration InitConfiguration()
        {
            var config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.test.json")
                .Build();
            return config;
        }
    }

To read the baseurl I am using the below code

private IConfiguration _iAppSettingConfiguration;
private static string _readonlypageUrl;
public GivenAccount(PlaywrightFixture playwrightFixture)
        {
            _iAppSettingConfiguration = IAppSettingConfiguration.InitConfiguration();
            _readonlypageUrl = _iAppSettingConfiguration["baseUrl"];
            
        }

This is working fine I am able to get the value for base URL. How can use IOption<> to read whole object. In my case I want to read user

enter image description here

Not able to find the bind method from Microsoft.Extensions.Configuration namespace

namespace Microsoft.Extensions.Configuration
{
  /// <summary>Represents a set of key/value application configuration properties.</summary>
  public interface IConfiguration
  {
    /// <summary>Gets or sets a configuration value.</summary>
    /// <param name="key">The configuration key.</param>
    /// <returns>The configuration value.</returns>
    string this[string key] { get; set; }

    /// <summary>Gets a configuration sub-section with the specified key.</summary>
    /// <param name="key">The key of the configuration section.</param>
    /// <returns>The <see cref="T:Microsoft.Extensions.Configuration.IConfigurationSection" />.</returns>
    IConfigurationSection GetSection(string key);

    /// <summary>Gets the immediate descendant configuration sub-sections.</summary>
    /// <returns>The configuration sub-sections.</returns>
    IEnumerable<IConfigurationSection> GetChildren();

    /// <summary>Returns a <see cref="T:Microsoft.Extensions.Primitives.IChangeToken" /> that can be used to observe when this configuration is reloaded.</summary>
    /// <returns>A <see cref="T:Microsoft.Extensions.Primitives.IChangeToken" />.</returns>
    IChangeToken GetReloadToken();
  }
}
3

There are 3 best solutions below

9
dhilmathy On BEST ANSWER

If you want user details as an object, you can have a class created and bind it to user section from your configuration.

Something like,

private IConfiguration _iAppSettingConfiguration;
private static string _readonlypageUrl;
public GivenAccount(PlaywrightFixture playwrightFixture)
{
    _iAppSettingConfiguration = IAppSettingConfiguration.InitConfiguration();
    _readonlypageUrl = _iAppSettingConfiguration["baseUrl"];

    var _user = new UserDetail();
    _iAppSettingConfiguration.GetSection(UserDetail.User).Bind(_user);
    
}

public class UserDetail
{
    public const string User = "user";

    public string UserName { get; set; } = string.Empty;
    public string Password { get; set; } = string.Empty;
}
2
Droa On

Option 1:

you can use the Services.Configure Method, when building your services.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0#configure-options-with-a-delegate

Option 2:

However, if you need to do it manually, you need to get a sub-section

var username = IAppSettingConfiguration.GetSection("user").GetValue<string>("username");
var password = IAppSettingConfiguration.GetSection("user").GetValue<string>("password");
2
AviacionnyUser On

Usual, if you want to get some field from your appsettings.json, you may to use Configuration methods that in WebApplicationBuilder at Startup.cs (at Program.cs in .NET 6)

{
  "Foo": {
    "bar": "someValue"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

For example, in case with appsettings.json file like that, we may get "bar" value by doing this (.NET 6 example)

var Foo = builder.Configuration.GetSection("Foo");
var Bar = Foo.GetSection("bar");

Or how it was before .NET 6.

public Startup(IConfiguration configuration)
{
  Configuration = configuration;
}
public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    var Foo = Configuration.GetSection("Foo")
    var Bar = Foo.GetSection("Bar")
}

I think this is the direction in which you need to think, good luck!