I have several applications in my cloud run using PHP and .NET Core. My existing ASP.NET Core Web API does not have an issue when trying to connect with my Cloud SQL (MySQL). The access with either Public IP or Private IP with VPC works just fine. However, I tried another app in Cloud Run with Blazor Server on .NET Core, connecting to the same database server is not working.
This is my connection string
"DefaultConnection": "Server=/cloudsql/my-project-id:asia-southeast2:my-cloud-sql; User ID=userDb; Password=verysecret; Database=mydb_dev"
I tried to connect with VPC either, creating a VPC serverless and attach it to my Blazor app.
So my connection string becomes like this:
"DefaultConnection": "Server=10.0.0.8; User ID=userDb; Password=verysecret; Database=mydb_dev"
The only time it works is when I changed the authorized networks from Cloud SQL to allow any IP Addresses (0.0.0.0/0). I'm using Entity Framework Core with package Pomelo.EntityFrameworkCore.Mysql
which is works with my ASP.NET Core Web API on another Cloud Run.
below is my dockerfile, in case if it's related
# Stage 1: Build the Blazor Server app
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build-env
WORKDIR /app
# Copy csproj and restore dependencies
COPY *.csproj ./
RUN dotnet restore
# Copy all the source code and build the app
COPY . ./
RUN dotnet publish -c Release -o /out /p:UseAppHost=false
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
# Expose port 80
USER app
EXPOSE 8080
EXPOSE 8081
# Copy published files
COPY --from=build-env /out .
ENTRYPOINT ["dotnet", "MyBlazorApp.dll"]
I resolve this based on @Curtis comment. this is dumb issue.
I had EF Scaffold in my Blazor, it's creating the OnConfiguring method in my DbContext class, and instead of getting connection string from appsettings.json, it is making hard coded like this
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySql("server=10.0.0.1;user id=appUser;password=myPass;database=mydatabase", Microsoft.EntityFrameworkCore.ServerVersion.Parse("8.0.31-mysql"));
}
I removed above lines and added these lines on program.cs
string connString = builder.Configuration.GetConnectionString("DefaultConnection") ?? string.Empty;
builder.Services.AddDbContext<MoccaDbContext>(options => {
options.UseMySql(connString, ServerVersion.AutoDetect(connString));
});
builder.Services.AddHttpContextAccessor();
the AddHttpContextAccessor
is important, because it will send the Connection String to DbContext. now it's working fine, I'm able to connect to Cloud Run both with Private & Public IP Address