asp.netsql-serverdocker.net-core

Untrusted Certificate Error when connecting to SQL Server running in Docker from .NET 7 API in VS2022


I have an API which I've upgraded from .NET Core 3.1 to .NET 7. It's now throwing an error when trying to connect to the database.

The error is:

A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.

I'm using VS2022, SQL Server (mcr.microsoft.com/mssql/server:2022-latest) is running in a Docker container.

I'm using Docker Compose:

version: '3.9'

services:
  sql-server-db:
    image: "mcr.microsoft.com/mssql/server:2022-latest"
    container_name: sql-server-db
    environment:
      MSSQL_SA_PASSWORD: "P@ssw0rd"
      ACCEPT_EULA: "Y"
    ports:
      - "1433:1433"
    volumes: 
      - sql1:/var/opt/mssql

volumes:
  sql1:
    external: false

The connection string is

server=127.0.0.1,1433;Initial Catalog=xxx;user id=sa;password=P@ssw0rd;Encrypt=False;TrustServerCertificate=True

From the posts I've read, either Encrypt=False or TrustServerCertificate=True should fix this issue, but neither, or indeed, both have helped.

I have confirmed that the SQL Server instance is running ok, I can connect using SSMS, using the username and password from the connection string.

Further, I can confirm that it's working with .NET 6, so it is definitely an issue with .NET 7 & EntityFrameworkCore 7.


Solution

  • I have managed to fix the issue.

    I changed my repositories to inject a IDbContextFactory<> and create a DbContext, rather than inject a DbContext object directly.

        public BookRepository(IDbContextFactory<SampleAPIContext> dbContextFactory, IRestToLinqParser<Book> parser, ILogger<BookRepository> logger) : base(dbContextFactory, parser, logger)
        {
        }
    

    and changed my Startup.cs to add the IDbContextFactory rather than the DBContext

            services.AddDbContextFactory<SampleAPIContext>(
                options => SqlServerDbContextOptionsExtensions.UseSqlServer(options, connectionString)
            );
    

    I'm not entirely sure why this made the difference, but it did.