Connecting .NET 8 Apps to MSSQL Databases Print

  • 0

Overview

Connect your .NET 8 application to Microsoft SQL Server databases hosted on our Windows platform.

Creating a Database in Plesk

  1. Log in to Plesk control panel
  2. Go to Databases
  3. Click Add Database
  4. Select MS SQL Server as the type
  5. Enter database name and create a user
  6. Note the credentials for your connection string

Installing Entity Framework Core

Add EF Core SQL Server package to your project:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

Connection String Format

Use this format in your appsettings.json:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=YOUR_DB_NAME;User Id=YOUR_USERNAME;Password=YOUR_PASSWORD;TrustServerCertificate=True;"
  }
}

Important: Include TrustServerCertificate=True to avoid SSL certificate validation errors in .NET 8.

Configuring DbContext

In Program.cs:

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

Production Connection String

For production, store connection strings securely:

Option 1: appsettings.Production.json

Create a separate file that is only deployed to production.

Option 2: Environment Variables

Set via web.config:

<environmentVariables>
  <environmentVariable name="ConnectionStrings__DefaultConnection" 
    value="Server=localhost;Database=mydb;User Id=user;Password=pass;TrustServerCertificate=True;" />
</environmentVariables>

Common Connection Issues

"A connection was successfully established...but then an error occurred during the pre-login handshake"

Solution: Add TrustServerCertificate=True or Encrypt=False to connection string.

"Cannot open database...Login failed"

Solutions:

  • Verify database name matches exactly (case-sensitive)
  • Confirm username and password in Plesk Databases section
  • Ensure user has permissions to the database

"A network-related or instance-specific error"

Solutions:

  • Use localhost as server (not IP address)
  • Database server should be accessible from your hosting

Testing Connection

Test your connection before deploying:

// In a controller or service
try {
    await _context.Database.CanConnectAsync();
    return "Connection successful";
} catch (Exception ex) {
    return $"Connection failed: {ex.Message}";
}

Was this answer helpful?

« Back