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)
2. Configure Dependency Injection in Program.cs
Ensure that appsettings.json
is properly loaded by adding builder.Configuration
in Program.cs
:
3. Run and Test
- Start your application.
- Navigate to:
- 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
:
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 specifyMACHINE_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