I have a class library that is used as a nuget package. The Nuget package will be used in one or more Web Api's.
I my class library, I want to be able to read the web api's configuration settings.
Can this be done with the Assembly.GetCallingAssembly(), which in this case is my web api?
The reason is that the web api's will have a connectionString that they get from Azure Key vault, and I want to read this connectionString in my class library(nuget package). I don't want want to pass the connectionString as a parameter to the nuget package. It should be fixed automagic.
I have tried something like this in my class library:
string path = Assembly.GetCallingAssembly().Location; // the web api
var config = ConfigurationManager.OpenExeConfiguration(path);
But I can't find the connectionString from the key vault here.
Here is the code in my Startup.cs in one of the web api's where azure key vault is added
public Startup(IWebHostEnvironment env)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json") appsettings.json in.
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
builder.AddUserSecrets<Startup>(); M
}
builder.AddKeyVaultConfiguration();
Configuration = builder.Build();
}
The connectionstring looks like this: Azure:Database:ConnectionString, and now I want to access this in my nuget package(Class library)
Related
I have a console app in .Net 6 and wondering how can I have multiple appSettings files?
I want to have one for
appsettings.development.json
appsettings.test.json
appsettings.production.json
I will be deploying the console application onto windows servers and hooking it up to a scheduled task. Depending on which environment I want a different appsettings to be used. I am not sure how to do this.
I think I would have to create an environment variable on each server to make it use the right file but hoping there is more a coding way automatically use the right appsettings file.
I found this posting that seems to be almost what I need but it is for web apps and not console apps
Automatically set appsettings.json for dev and release environments in asp.net core?
You can pass environment variable via line argument, like this
C:\Myapp.exe --environment Development
EDT.
Then, (just because you have console app) you need to install Microsoft.Extensions.Configuration.CommandLine and Microsoft.Extensions.Configuration.Json packages from nuget.
After intall, get your line argument in IConfigurationRoot with:
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.Build();
Retrive your environment variable:
var environmentName = config["environment"];
And finally, build your config from appsettings.json:
var myConfig = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{environmentName}.json")
.Build();
How can I configure application insights telemetry for an asp.net framework 4.7.1 web application that uses appsettings.json configuration files? I tried checking the Microsoft documentation but it just shows setup for ASP.NET apps that use xml-based configuration.
EDIT: Here is the part of the Startup.cs file that shows I am using appsettings.json.
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
SCENARIO - 1
This works in case of .net framework 4.7.1 web application which have no auto generated appsettings.json file.
Navigate to your Project > Add Application Insights Telemetry > Application Insights Sdk (local) > Next > Finish > Close
In applicationinsights.config file, while Adding Application Insights automatically we need to add instrumentation key to ApplicationInsights.config before closing the </ApplicationInsights> tag file.
<InstrumentationKey>"your-instrumentation-key-goes-here"</InstrumentationKey>
And then update each Microsoft.ApplicationInsights NuGet package to the latest stable release by navigating to Project > Manage NuGet Packages > Updates.
If Adding Application Insights Automatically isn't working, then you can try manually from HERE.
REFERENCE : Configure monitoring for ASP.NET with Azure Application Insights
SCENARIO - 2
You can have application Insights configuration set from your appsettings.json file when you have one in your project
Navigate to your appsettings.json file and add your instrumentation key for your application Insights like mentioned inthe below reference.
Application Insights comes in the form of a Nuget package. Review the .csproj file of the web project and look for the Application Insights package added.
Now navigate to your startup.cs project and add services.AddApplicationInsightsTelemetry(Configuration); to your ConfigureServices method.
Navigate to Configure method and add
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
REFERENCE : Monitoring Applications using Application Insights
I'm attempting to connect to my ASP.NET Core Web API application (.NET 6 in Visual Studio 2022 Preview) with SQL Server. And I tried to use the following code to configure the connection string in the Startup class as I used to.
services.AddDbContext<DEMOWTSSPortalContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
But in .NET 6, I recognize that Startup and Program classes are merged into one class. And the above code is not usable in .NET 6. AddDbContext is not recognized. So do you have any idea or documentation about this update, and how to configure connection strings in .NET 6?
Configuration.GetConnectionString(string connName) in .NET6 is under builder:
var builder = WebApplication.CreateBuilder(args);
string connString = builder.Configuration.GetConnectionString("DefaultConnection");
also AddDbContext() is under builder.Services:
builder.Services.AddDbContext<YourContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
.Net 6 Simplifies a lot of a tasks and introduces WebApplicationBuilder which in turn gives you access to the new Configuration builder and Service Collection
var builder = WebApplication.CreateBuilder(args);
Properties
Configuration : A collection of configuration providers for the application to compose. This is useful for adding new configuration sources and providers.
Environment : Provides information about the web hosting environment an application is running.
Host : An IHostBuilder for configuring host specific properties, but not building. To build after configuration, call Build().
Logging : A collection of logging providers for the application to compose. This is useful for adding new logging providers.
Services : A collection of services for the application to compose. This is useful for adding user provided or framework provided services.
WebHost : An IWebHostBuilder for configuring server specific properties, but not building. To build after configuration, call Build().
To add a DbContext to the Di Container and configure it, there are many options however the most straightforward is
builder.Services.AddDbContext<SomeDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
Nugets packages
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer to use UseSqlServer
You can try to read in your controller like this..
private readonly IConfiguration _configuration;
public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
{
_logger = logger;
string _configuration = configuration.GetSection("connectionStrings").GetChildren().FirstOrDefault(config => config.Key == "Title").Value;
}
NOTE: You can get the value based on the key provided above.
Install Packages
Microsoft.Extensions.Configuration.dll
Microsoft.Extensions.Configuration.FileExtensions.dll
Microsoft.Extensions.Configuration.Json.dll
Add Name Spaces in Controller
using Microsoft.Extensions.Configuration;
using System.IO;
Add Code in
Controllervar objBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appSettings.json", optional: true, reloadOnChange: true);
IConfiguration conManager = objBuilder.Build();
var my = conManager.GetConnectionString("DefaultConnection");
In appsettings.json Add Code:
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
},
When I set up a .NET Core v3 Razor web application the startup.cs file contains what I should need in order to access settings/values from the appsettings.json file;
public IConfiguration Configuration { get; set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
According to the docs I should then be able to use;
Configuration["mysetting:variable"]
Anywhere to access it. However I get the build error 'The name 'Configuration' does not exist in the current context'.
In order to solve this I have manually built the configuration using;
ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("mysetting")["variable"]
but it's meant to do that already isn't it? I know this has changed in v3 in v2 you did need to build the configuration.
Try adding this #inject statement to the top of your razor page:
#inject Microsoft.Extensions.Configuration.IConfiguration Configuration
After that, you should be able to access the config settings using this injected field:
var mySettingVariable = Configuration["mysetting:variable"];
I have 5 Project in One solution In that Email service is one of the Class library i have when i try to get the Directory path its return main project path only here my code.
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory()+ ".EmailService")
.AddJsonFile("appsetting.json");
IConfigurationRoot configuration = builder.Build();
extra i have added a ".EmailService". there is any solution to get path?
For .Net Core
Inject IHostingEnvironment env
string path =env.ContentRootPath;
For .Net framework
string _systemPath=System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;