I am trying to access App configuration with a simple console app. So far I have:
static void Main(string[] args)
{
IConfiguration config = new ConfigurationBuilder()
.AddUserSecrets("e7315677-d6aa-41ab-b7cc-8e801a7c8ae9")
.AddAzureAppConfiguration("ConnectionStrings:AppConfig")
.Build();
Console.WriteLine("Hello World!");
}
But an exception is thrown indicating that
System.ArgumentException: 'Connection string doesn't have value for keyword 'ConnectionStrings:AppConfig'.'
I have put this connection string in secrets.json and I know that it is valid. What am I doing wrong?
{
"ConnectionStrings:AppConfig": "<my connection string>"
}
Thank you.
Kevin
Make sure the connection string begins with "Endpoint=". It's looking for key/value pairs, and interprets a value without a key as a key without a value.
The AddAzureAppConfiguration method expects a connection string as an argument. You receive System.ArgumentException since "ConnectionStrings:AppConfig" is not a valid connection string.
In order to use the connection string defined in the user secrets to initialize the Azure App Configuration provider, we can first build an IConfiguration instance with the user secret and use it to access the connection string property. Here's a modified version of your code that works.
static void Main(string[] args)
{
IConfiguration intermediate = new ConfigurationBuilder()
.AddUserSecrets("e7315677-d6aa-41ab-b7cc-8e801a7c8ae9")
.Build();
IConfiguration configuration = new ConfigurationBuilder()
.AddAzureAppConfiguration(intermediate["ConnectionStrings:AppConfig"])
.Build();
}
Don't make the same mistake I did and copy the endpoint from the Azure App Service portal. Look for the primary key section and there is a copy button there for the connection string. It should then give you aa string that includes that starts Endpoint= and includes the id and secret
Related
Started a new Console app in .NET 6 and am adding Dependency Injection. In the code below, how can I get access to the IConfiguration object to read a value from appsettings (after calling Build?
The configuration is available within the StoreFactory service, as its injected via the constructor, but if I want to read values from appsettings within the main section of code within program.cs, how can I get at it?
program.cs
var SvcBuilder = new HostBuilder()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(Directory.GetCurrentDirectory());
config.AddJsonFile("appsettings.json", optional: true);
config.AddEnvironmentVariables();
if (args != null)
{
config.AddCommandLine(args);
}
})
.ConfigureServices((hostContext, services) =>
{
services.AddLogging(configure => configure.AddConsole())
.AddTransient<IStoreFactory, StoreCtxFactory>();
});
var host = SvcBuilder.Build();
The Host.CreateDefaultBuilder defines the behavior to discover the JSON configuration and expose it through the IConfiguration instance. From the host instance, you can ask the service provider for the IConfiguration instance and then ask it for values.
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using IHost host = Host.CreateDefaultBuilder(args).Build();
// Ask the service provider for the configuration abstraction.
IConfiguration config = host.Services.GetRequiredService<IConfiguration>();
// Get values from the config given their key and their target type.
var configValueInt = config.GetValue<int>("yourKeyName");
string configValueStr = config.GetValue<string>("yourKeyName");
For more information read the Docs.
What is the correct way of obtaining the remote IP address (the address of the client making the request) in an Azure durable function?
The beginning of my HttpStart method
public static async Task<HttpResponseMessage> HttpStart(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "report-data/get")]
HttpRequestMessage req,
[DurableClient] IDurableOrchestrationClient starter, ILogger log)
{
I tried
((HttpContext)req.Properties["MS_HttpContext"]).Connection.RemoteIpAddress.ToString(); but the MS_HttpContext property is missing.
I also tried
string result = string.Empty;
if (req.Headers.TryGetValues("X-Forwarded-For", out IEnumerable<string> headerValues))
{
result = headerValues.FirstOrDefault();
}
return result;
which returns and empty string.
I have looked at this similar question, but it assumes the request is of type HttpRequest. In my case, it is HttpRequestMessage.
This answer suggests that the X-Forwarded-For header must be enabled first. But I don't know how to do this in my Azure Function App (or for my durable function).
I am developing my Azure functions locally, using VS Code.
After a bit of trying, I have managed to adapt this answer to my Azure Durable Function. I also found this information on how to use dependency injection in Azure functions quite handy. The steps were as follows:
Add the following method to the project's Startup class in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
Add the folowing using statement to Startup.cs:
using Microsoft.AspNetCore.Http;
Add the following private member and constructor to my orchestrator class
private readonly IHttpContextAccessor _accessor;
public GetReportActionsOrchestration(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
Add the following function for getting the client IP address to my orchestrator class:
private string GetClientIpAddress()
{
string ip = _accessor.HttpContext?.Connection?.RemoteIpAddress?.ToString();
return (string.IsNullOrWhiteSpace(ip)) ? string.Empty : ip;
}
Modify the durable orchestration code to be compatible with dependency injection by removing static modifier from the orchestration's HttpStart and RunOrchestrator functions.
Add string remoteIpAddress = this.GetClientIpAddress(); to HttpStart function to get the client's IP address, which can then be passed to RunOrchestrator as a parameter.
Changes to the orchestrator class require
using Microsoft.AspNetCore.Http;
using System;
I'm working with a C# class that reads from appsettings using
Environment.GetEnvironmentVariable("setting")
I want to make another console program (.net core 3.0) that reads settings from appsettings.json and loads them into environment variables.
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
IConfiguration config = builder
.Build();
var businessLogic = new BusinessLogic(); // uses GetEnvironmentVariable to get configuration
}
In my business logic class, the environment variables aren't getting pulled back correctly. What might be the problem?
appsettings.json is in this format:
{
"SETTING" : "setting value"
}
Environment.GetEnvironmentVariable("setting") will always try to read the data from an environment variable, not from your loaded config.
You need to change your BusinessLogic class to accept the config object you built and use that to access the settings. An example:
public class BusinessLogic
{
public BusinessLogic(IConfiguration config)
{
var value = config.GetValue<string>("SETTING");
}
}
In this example value will contain the correct value of SETTING if it was last set in appsettings.json or using an environment variable.
I am a new learner for pact and I want to know what should I input when do provider verification
for provider verification I should fill provided target as localhost only or instead of localhost i also can input actual env's host? which scenario is the best for contract test?
public class LoginProviderTest {
private static final Logger LOGGER = LoggerFactory.getLogger(LoginProviderTest.class);
#TestTarget
public final Target target = new HttpTarget(?????);
if you are using Springboot, you can try like,
#TestTarget
public final Target target= new SpringBootHttpTarget();
I am working with AspNet Core 2.0, I have a situation where I have a context but the connection string is dynamic as per selected by the user at runtime.
Add-Migration doesn't work as it wants to have the connection string to match migration history.
var datastore = _MainDBContext.datastores.FirstOrDefault(x=>x.db_type=="MS");
string connectionString = #"Server=" + datastore.db_instance_ip + ";Port=3306;Database=" + datastore.db_name + ";Uid=" + datastore.db_user + ";Password=" + datastore.db_pass + ";";
optionsBuilder.UseMySQL(connectionString);
_MSDBContext= new MSDBContext(optionsBuilder.Options);
_MSDBContext.Database.Migrate();
Error
No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
I want the migrate to create the database along with tables dynamically. Any help is appreciated.
Thanks
The error message says your DbContext needs a constructor which accepts a DbContextOptions.
public MSDBContext(DbContextOptions options) : base(options)
{
}
Or you could try the following approach (inside of your context class):
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var connectionString = configuration.GetConnectionString("NAME_OF_CONNECTION_STRING");
optionsBuilder.UseSqlServer(connectionString); //or any other DB provider
}
}
Of course, you can use different logic to get the connection string. You don't need to use appsettings.json file.