ASP.NET Core Web API - ConnectionString in project reference - c#

I have a ASP.NET Core Web API project added to my solution. It uses a project dependency which connects to SQL Server database, using a connection string like this:
public string connectionString = ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;
This works fine, another Web/WinForm Apps uses this library and connects to SQL Server instance (the connection string is set in the web.config or app.config)
The problem:
The ASP.NET Core Web API project fails to use the connection string from the library, I have set appsetting.json:
"ConnectionStrings": {
"ConnectionName": "Data Source=database;Initial Catalog=catalogname;User ID=username;Password=password;"
},
But always the connection string with the connection name is null, and has:
data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true

It seems ConfigurationManager failed to read json file,have you tried add a .config file in your WebApi project?
I tried two solutions as below :
public class Class1
{
public string? con1 { get; set; }
public string? con2 { get; set; }
public readonly IConfiguration Config;
public Class1()
{
//read connectstring from .config file
con1 = System.Configuration.ConfigurationManager.ConnectionStrings["ReadConnectStringContext"].ConnectionString;
Config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();
//read connectstring from appsettings.json
con2 = Config.GetConnectionString("ReadConnectStringContext");
}
}
The structure:
The Result:

Here is the documentation from MS:
Class libraries can access configuration settings in the same way as executable apps, however, the configuration settings must exist in the client app's App.config file. Even if you distribute an App.config file alongside your library's assembly file, the library code will not read the file.
A quick fix for you is to place the correct DB connection string section in the Web/WinForm Apps settings file.
If you really want to use the app settings from the library project, using a custom setting to reference the app settings from in the library project. Here is the reference.

Related

What is the right way to add app.config to a .net core wpf application since it doesn't come with it unlike .net framework?

I like setting my connection string in my app.config and this has been very easy for me for a .net framework. Since I migrated to .net core I noticed that it doesn't come with app.config.
In .NET Core and ASP.NET Core applications the application settings are stored in a JSON file named appsettings.json. This is the default configuration for .NET Core projects. INI and XML files is also supported but JSON is the default.
You may also added to .Net Core WPF project appsettings.json config file, for this you need to install following nuget packegs:
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json
Microsoft.Extensions.DependencyInjection
after this,
{
"ConnectionStrings": {
"myDataBaseConnectionString": "Server=myServer;Database=myDataBase;Trusted_Connection=True;"
}
}
and you can read it in your code by calling the GetConnectionString method in the Microsoft.Extensions.Configuration namespace.
var myDbConnectionString = _configuration.GetConnectionString("myDataBaseConnectionString");
Second way, you may use static class for keeping your database connection data:
public static class dbConfig
{
public const string ConnectionString =
"Data Source = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (COMMUNITY = TCP)(PROTOCOL = TCP)(HOST =192.100.10.11)(PORT = 1521)))(CONNECT_DATA = (SID = testdb))); User Id =admin; Password=admin;Pooling=true";
}
and you may use from it any place of your assambly

A named connection string was used, but the name was not found in the application's configuration

I am developing an ASP.NET Core 3.0 Web API Application with EF CORE Database-First approach, however I am facing a strange error while accessing the database context from API Controller.
Error Message:
A named connection string was used, but the name 'GPMS' was not found
in the application's configuration. Note that named connection strings
are only supported when using 'IConfiguration' and a service provider,
such as in a typical ASP.NET Core application. See
https://go.microsoft.com/fwlink/?linkid=850912 for more information
My Connection string in appsettings.json file:
"ConnectionStrings": {
"GPMS": "Data Source=SERVER_IP;Initial Catalog=GPMS;User Id=DB_USER;Password=DB_PASSWORD"
}
I have also tried connection string in this way:
"ConnectionStrings": {
"GPMS": "Server=SERVER_IP;Database=GPMS;User Id=DB_USER;Password=DB_PASSWORD"
}
I have registered it in IService in Startup.cs as below:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<GPMSContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("GPMS")));
}
But no luck in this. Can anyone help me to rectify the issue?

EF how pass connection string to a different project

I've a solution with different projects. I'm using EF6 in my 'DALProject' structured with a repository pattern. What I need to do is to make CRUD operations from another project called 'MainProject' that references the one above, but I receive this error: `
No connection string named 'MyEntity' could be found in the application config file
To resolve this my idea is to pass directly the connection string to the DBContext constructor.
So I copied in an external file the connection string that is in the App.Config of my DALProject, and then I'm going to read this file from the MainProject. This is the connection string:
metadata=res://*/My_Model.csdl|res://*/My_Model.ssdl|res://*/My_Model.msl;provider=System.Data.SqlClient;provider connection string="data source=192.xxx.xxx.xxx\SQL2008R2EXP;initial catalog=My_Catalog;persist security info=True;user id=sa;password=xxxxxx;multipleactiveresultsets=True;application name=EntityFramework"
When this is done I try to set the DBContext in this way:
public class My_Entities : DBContext{
public My_Entities(string connStr)
: base (connStr){}
}
But what I got is this error: `
No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'. Make sure the provider is registered in the 'entityFramework' section of the application config file. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.`
Any helps?

Web Api project with another data project both have entity framework only wanting connection string in data project

I have 2 projects: 1 Web api (ReportingApi) 2. Data (ReportingApi.Data)
Web Api will not connect to the class library (Data ) project without a connectionstring in web.config that is duplicate of my connectionstring in my Data project app.config.
Both have
<connectionStrings>
<add name="ScriptsContext" connectionString="Data Source=SQLserverblah;Initial Catalog=blahdb;User ID=blah;Password=blah" providerName="System.Data.SqlClient" />
</connectionStrings>
Data project DbContext
public class ScriptsContext : DbContext
{
public DbSet<Question> Questions { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<ScriptsContext>(null);
modelBuilder.Entity<Question>().ToTable("Question", schemaName: "dbo");
}
}
The only config that is read is the config for the executing project. I.E. you are running the Web API website and it's config is used.
If you want Data project to be a black box, you will need to hard code the connection string or get it from a source other than configuration.
If you want to test this theory, you can remove the connection string from the Data project and still start Web API. The only reason you would need the connection string in the Data project is if you are using an ORM, like Entity Framework, that allows you to update the generated code files within Visual Studio.
Hope this helps.

How to connect to the connection string written in the web.config of the web services

We have a web service project called 'Service' and in the web.config of the 'service' I have set the connection string as follows:
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=L308;Initial Catalog=Dashboard;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
I am trying to access the connection string from another project 'DBConnector' using the following code but getting null reference exception even though after adding the reference of the 'Service' into 'DBConnector'. using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
You will need to have the connection string in DBConnector project config file. Adding reference to a project doesn't bring in the config of that project in the main config of the project
If i got you
You can not do that if you want to use the Connection string of service in you library. You need to expose that as property or method
in you service.cs
public string connectionstring
{
get
{
return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
}
}
or
DBConnetor added as referance
If the DBconnector has added as referance in the Service layer than you can access it easily by the code you have written
If you need want to make that connection string Global so all you applications and services can use it you will need to put it in the machine.config.
The machine config if found here %WinDir%\Microsoft.NET\Framework\\CONFIG.
'Service' into 'DBConnector'.
Seems to be incorrect thing to do. It should have been other-way around!

Categories

Resources