3

I have a test project with ASP.NET Core and trying to read the appsettings 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 Answers 3

2

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;
}
Sign up to request clarification or add additional context in comments.

9 Comments

I don't have any Bind(_user) function, do I need to add some dependency ? I am using Asp.net core 5
You should be having it. It is learn.microsoft.com/en-us/dotnet/api/…
No I don't see any bind function, updated on the question with screenshot
you need to add the namespace Microsoft.Extensions.Configuration
Thanks it is working fine, was looking for this answer, Just I need to add <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="5.0.0" /> package
|
0

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 Comments

I am using the test project as a c# class library project. I don't have WebApplication.CreateBuilder(args)
to keep it simple, I added another solution without the ioption-pattern...
0

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!

2 Comments

I don't have any startup class, since I am using test project as c# library project
Sorry, it seemed to me, that is the asp.net project. So, there is no difference, you need to use IConfiguration to work with appsettings. And about the part of question that was edited hour ago: you can't get user as object from json, but you can get params of user as sections, and create object as class instance with fields taken from those sections, for example. Sorry if something is wrong, for my english.

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.