ASP.Net Core Web API works on IIS Express, but not working when deployed to IIS - c#

I'm new to ASP.Net Core. I have an ASP.Net Core Web API project through which you can connect to a local MS SQL database and perform CRUD operations for the database. The Web API works just fine when running on IIS Express -- it launches the Chrome browser, retrieves records from the local SQL database, and displays the values on the Chrome browser. But the problem is, the Web API does NOT work when deployed to IIS (that is, when published to a folder and being run on IIS.)
I guess the problem is about connecting to the MS SQL database. I'm suspecting that connecting to the database works fine on IIS Express, but fails to connect when deployed to IIS for some reasons. But I'm not sure. The following is the connection string:
// Connection String=> "Data Source=.\\SQLEXPRESS01;Initial Catalog=mynotedb;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddMvc(option => option.EnableEndpointRouting = false)
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddNewtonsoftJson(opt => opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
services.AddDbContext<mynotedbContext>(options => options.UseSqlServer("Data Source=.\\SQLEXPRESS01;Initial Catalog=mynotedb;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"));
}
I have an identical SQL database copied on my Azure account, and the web API works just fine for the Azure SQL database. It works fine both when run on IIS Express and deployed to IIS when it connects to the Azure database. For the Azure SQL database, the connection string is as the following:
services.AddDbContext<mynotedbContext>(options => options.UseSqlServer("Server=tcp:mynote1.database.windows.net,1433;Initial Catalog=mynotedb;Persist Security Info=False;User ID=mylogin;Password=mypassword;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"));
Please help me with this issue. I've been trying to find the solution for the whole day with no success. Thank you in advance!

first step check database connection work currently and TrustServerCertificate=True
next step check permission folders on your host or your service provider

Related

ASP.NET Core 6 - SqlConnectionStringBuilder not reading environment variable

I am using SqlConnectionStringBuilder to create my connection string. This is because I keep my database passwords in secrets.json for local development and in environment variables on the servers under IIS --> Website name --> Configuration Editor, Section: system.webServer/aspNetCore, From: ApplicationHost.config <location path='WebsiteName'/>.
I have done this in ASP.NET Core 3.1 with no issues. Currently I'm working on a site that was started in ASP.NET 5 and updated to ASP.NET Core 6. I'm using local db for local dev so in this instance there's no need for a database password in secrets.json (although I still use it for other secrets).
Whenever I try to run my website I get an error in the Windows Logs stating:
System.Data.SqlClient.SqlException (0x80131904): Login failed for user 'UserName'.
Another log entry right before it reads:
Login failed for user 'UserName'. Reason: Password did not match that for the login provided. [CLIENT: IP Address of Server]
If I hard code the password into the connection string in appsettings the website runs without issue. I can even get the database password from environment variables and display it on the page so I know the website is able to access them. However, if I inject the environment variables into the connection string, it's somehow injecting the wrong password or not working in some other way.
I've spent days on this issue and can't figure it out. The SQL Server user is set as an admin, and has dbowner rights to the database as well.
My code in startup.cs looks like this:
private string _csSqlDb = null;
And then inside public void ConfigureServices
var csBuilder = new SqlConnectionStringBuilder(
Configuration.GetConnectionString("SqlDb"));
// Development uses local db so no password
if (!Environment.IsDevelopment())
{
csBuilder.Password = Configuration["DbPassword"]; //use with .NET Core 3.1 and it works
//csBuilder.Password = System.Environment.GetEnvironmentVariable("DbPassword");
}
_csSqlDb = csBuilder.ConnectionString;
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(_csSqlDb));
Here are the connection strings I am using.
Local development (uses Windows Authenitcation to localdb) :
"ConnectionStrings": {
"SqlDb": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=DbName;Integrated Security=True;Connect Timeout=60;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
}
Staging Server (Uses SQL Server Authentication to SQL Server Express 2019):
"ConnectionStrings": {
"SqlDb": "Data Source=IPAddress\\SQLExpress;Initial Catalog=DBName;Persist Security Info=True;Trusted_Connection=False;User Id=UserName"
}
If anyone has any insights or ideas as to what the problem can be, I would be very grateful. This issue is happening on my local Windows Server 2019 Standard running SQL Server 2019 Express, and also on a production server running Windows Server 2019 Standard running SQL Server 2017 Web Edition.

When I run my ASP.NET Core MVC solution from another user it does not connect to the SQL Server database

I have created a simple ASP.NET Core MVC application in Visual Studio. I also created a database using EF Core code first approach. The database uses Windows authentication.
The connection string I used was
Server=(local)\\sqlexpress;Database=LibraryEmployeeDB;Trusted_Connection=True;
I am supposed to send this project to my professor but when I tried to run the project from a different user on my computer it doesn’t work because I can’t connect to the database with the other user.
I tried to change to Windows and SQL Server authentication and create a new user and add that to the connection string but that didn’t work either. I would be so grateful for any tips on how to solve this problem so that my professor can run the project as it is supposed to. Thank you!
You should run init command to create the database :
"Update-Database" in the Package manager console in the Visual studio.
Your Connection String shulde be like this:
"ConnectionStrings": {
"ConnStr": "Data Source=(local)\\sqlexpress;Initial Catalog=LibraryEmployeeDB;Integrated Security=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;Trusted_Connection=false;User ID=yourUsername;Password=yourPassword;"
}
and in Startup.cs you have to use this section:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<YourContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnStr")));
//and other things
}

Web-Api dontnet core 2.2 running on centos 7 mysql not working

I built this creating-web-apis-using-asp-net-and-mysql-in-5-minutes
The api runs fine on my local machine windows 10 with visual studio 2017 enterprise. I have a centos box running on VMware in another location this is where my MySQL database is. When I run the api on my local machine I use a connection string with a FQDN and the api runs fine. FYI the api also has a method without database access that basically sends back a json string ["value1","value2"] both this and the one that gets a user from MySQL work fine on local machine.
Next I set it up as a service on the Centos box and set up apache to proxy to the kestrel web server at localhost:5000 using these instructions Host ASP.NET Core on Linux with Apache. my Apache virtual host config is the same as the one in the example except no server alias and no logging. I didn't want a server alias and the logging commands stopped the service from starting. I also needed to upgrade apache from the Centos's repo apache 2.4.6 to Apache 2.4.36 I think.
I did this using a third party repo because RequestHeader set "X-Forward-Proto" expr=%{REQUEST SCHEME} needed Apache 2.4.10 or above.
It should be stated that I used my own database and not the example one it is basic just returns user info like uname etc.
If I run http://MyFQDN/api/values I get the desired response.
If run http://MyFQDN/api/users/1 which when run on my local machine while debugging returns a json string with the correct information using a MySQL connection string with a FQDN and not localhost:3306 or 127.0.0.1:3306 as the server in the connection string. When I try it on the Linux box no go.
Instead I get the infamous http 500 error which I believe means that program is not running correctly the only difference here is the MySQL connection string or there is something else.
in the demo it says
Some values (for example, SQL connection strings) must be escaped for the configuration providers to read the environment variables. Use the following command to generate a properly escaped value for use in the configuration file
However I have tried several times using the example
systemd-escape … see demo for exact syntax as it doesn't escape well here funny.
I believe if I had a properly escaped MySQL connection string that would work on kestrel in the Centos box it might work.
This is in appsettings.production.json
"ConnectionStrings": {
"DevDatabase": "Server=127.0.0.1;Port=3306;Database=nameOfDatabase;Uid=svcuser;Pwd=Password;"
},
Any help would be appreciated
Thanks
________--------UPDATE
So I am trying to attach the visual studio debugger to the web-api using ssh which I believe should let me walk through the code while it is running on the Centos box and find the error.
Here is link to instructions to do just that (FYI no luck yet) Link to instructions
Any advice on this or some other help always accepted
Thanks
use the instructions under my update. I am now able to run the web-api on the Linux box through any browser and step through the code on my machine …….
I have a null object at my connection string from the .json file.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<sPPContext>(options =>
options.UseMySQL(Configuration.GetConnectionString("changedButFrom.json")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
}
the error happens on the line where I put changedButFrom.json I am confident it is the escaping of the connection string that is causing the problem before I wasn't sure what the problem was
Great tool

Publish C# application with SQL Server database

My application does basic CRUD operations over an external .mdf file. The database file is created separately in SSMS. On my PC, everything works perfectly fine. When I install it on someone else's computer, it refuses to connect to the database. The other PC also has the same database at the exact same location.
The connection string I am using is (in app.config):
conString=Data Source =.\sqlexpress; Initial Catalog = dbName;
Integrated Security = True; Pooling = False
In my code:
dbConnection = new SqlConnection(Settings.Default.conString);
The other PC has SQL Server installed as well. Tried going through almost all the results but almost all of them suggest either
Adding the existing database with the project. I can't seem to do that because when I try that I get an error:
permission denied
I can't rewrite the whole code with a service based database pre-attached to it.

WCF Service Error accessing DB

I have a WCF Service running under IIS 7.0. The app pool identity is set to a user account lets call it "MyDomain\MyAcc." I have given "MyDomain\MyAcc" login permissions to the SQL 2005 Server, and the two DBs that it uses on that server.
When I try to invoke one of the WCF methods I get the following in my logs:
"Login failed for user 'MyDomain\MyAcc'..." I have tried removing and re-adding that user on the SQL Server.
I also tried accessing the DBs from Management Studio running as "MyDomain\MyAcc" and that worked.
What am I missing?
Finally Figured it out, we are using LINQ to SQL and the last guy who checked the code in commented out the code that we used to pass in the connection string from the web.config file. So it was using the connection string from the dbml file instead. That connection string was pointing to a DB that the user account did not have access to.

Categories