Is there a best way to change the appsettings.json option that ASP.NET uses for each HTTP request?

Asked 2 years ago, Updated 2 years ago, 141 views

ASP.NET Core is loading options from appsettings.json (ASP is amateur).
I'd like to change the options I use depending on the parameters of the HTTP request, is there any best way?
I was able to move it just in case, but I would like to ask you something that I would like to improve.

For example, appsettings.json is

{
  "params": [
    "a": {
      "name": "Alice"
    },
    "b": {
      "inherit"—true
    }
  ],
  "default": {
    "name": "Default"
  }
}

The optional class is set to

public classExampleOptions{
  public const string Example="Example";
  public string? Name {get;set;}
  public bool?Inherit {get;set;}
}

The class you are using is

public classExample{
  ExampleOptions m_options;
  publicExample(IOOptions<ExampleOptions>options){/*I want to make it IOptionsSnapshot to indicate that it is not fixed*/
    m_options=options.Value;
  }
}

Registration is now available at

public static IHostBuilderCreateHostBuilder(string[]arg){
  return Host.CreateDefaultBuilder (args)
        .ConfigureServices((hostContext,services)=>{
           services.AddScope(provider=>{
             returnGetParamExamExamExampleOptions>ExampleOptions>(
               hostContext.Configuration,
               provider,
               ExampleOptions.Example);});
         })
        .ConfigureWebHostDefaults(webBuilder=>{
           webBuilder.UseStartup<Startup>();
         });
}
public static IOptions GetParamExampleOptions <T>(
  ICconfiguration configuration, IServiceProvider provider, string sectionName) {
  varcontext=provider.GetRequiredService<IHttpContextAccessor>();
  varparam=context.HttpContext!.GetRouteData().Values["param"] as string;
  var options=configuration.GetSection($"params:{param}:{sectionName}").Get<T>():
  var inMemoryOptions = new Dictionary <string, string>();
  // If Inherit is true, generate an in-memory option that copies the parameter "default"
  // Actually, since Inherit functions are used in multiple options, it is more complicated because it would be easier to use the same string operation.
  var InheritedOptions = new ConfigurationBuilder()
    .AddInMemoryCollection (inMemoryOptions)
    .Build().GetSection($"params:{param}:{sectionName}";
  return Options.Create(inheritedOptions); /*I want to create an IOptionsSnapshot here*/
}

Now I can change the options for each request, but I would like to use IOptionsSnapshot instead of IOptions.

If you register with services.AddOptions(), the user will automatically switch between IOptions and IOptionsSnapshot, but I didn't know how to specify the option to switch per request.

Inherit inherits the Default option, which can be complicated.
Is there anyone who knows how to implement it smarter?

asp.net-core

2022-09-30 19:44

1 Answers

I was able to change from IOptions to IOptionsSnapshot, so I would like to resolve it once.

returnOptions.Create(inheritedOptions); /*I want to create an IOptionsSnapshot here*/

This is done using OptionsManager, a derivative of the IOptionsSnapshot, as shown below.

return new OptionsManager<T>(
    new OptionsFactory<T>(
        newIConfigureOptions <T> [ ]
        {
            new ConfigureOptions <T>(opt=>
            {
                Resolved because I noticed that there was an inheritOptions.Bind(opt); /*Bind()*/
            })
        },
        Enumerable.Empty<IPostConfigureOptions<T>>()
    )
);

Thank you all for your confirmation.


2022-09-30 19:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.