Tuesday, February 25, 2025

Test the connection string in your ASP.NET Core MVC

 To test the connection string in your ASP.NET Core MVC application, follow these steps:


1. Inject and Read Connection String in a Controller

You can inject IConfiguration into a controller and check if the connection string is being read correctly.

Modify HomeController.cs (or create a new controller)

csharp
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using System.Data.SqlClient; namespace YourNamespace.Controllers { public class HomeController : Controller { private readonly IConfiguration _configuration; public HomeController(IConfiguration configuration) { _configuration = configuration; } public IActionResult TestConnection() { string connectionString = _configuration.GetConnectionString("ConnStrMVC"); try { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); return Content("Database Connection Successful!"); } } catch (Exception ex) { return Content("Database Connection Failed: " + ex.Message); } } } }

2. Configure Dependency Injection in Program.cs

Ensure that appsettings.json is properly loaded by adding builder.Configuration in Program.cs:

csharp
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); // Make sure appsettings.json is properly loaded builder.Services.Configure<YourAppSettings>(builder.Configuration.GetSection("ConnectionStrings")); var app = builder.Build();

3. Run and Test

  • Start your application.
  • Navigate to:
    arduino
    https://localhost:port/Home/TestConnection
  • If the connection is successful, it will show "Database Connection Successful!"
  • If there is an issue, the error message will be displayed.

4. (Optional) Test in Program.cs Before Running the App

If you want to test before the application starts, add the following in Program.cs:

csharp
string connectionString = builder.Configuration.GetConnectionString("ConnStrMVC"); try { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); Console.WriteLine("Database Connection Successful!"); } } catch (Exception ex) { Console.WriteLine("Database Connection Failed: " + ex.Message); }

Then, run the project and check the Output Console for results.


5. Verify SQL Server

If the connection fails, check:

  • SQL Server is running (services.msc → SQL Server is started)
  • Correct server name (. or (local) for local SQL, or specify MACHINE_NAME\SQLEXPRESS if using SQL Express)
  • TrustServerCertificate=True if using Windows Authentication
  • Use User ID=sa;Password=yourpassword; if using SQL Authentication

This method ensures that your connection string works before implementing database operations.

No comments:

Post a Comment