Common .NET Errors and How to Fix Them

DotNET development is great until you hit an error that makes you wonder if you should switch careers. Whether you’re working on a web application, a backend service, or a SaaS platform, you’ll inevitably run into some frustrating .NET issues.

Instead of spending hours debugging, let’s go over some of the most common .NET errors, why they happen, and how to fix them fast. I’ve personally run into these while working on real-world applications, so I’ll share practical fixes that have saved me hours of frustration.

1. NullReferenceException: Object reference not set to an instance of an object

This error is so common that if I had a peso for every time I saw it, I’d probably be retired by now.

Why This Happens

You’re trying to use an object that hasn’t been initialized. For example, let’s say you’re fetching transaction details from an API:

C#
var amount = transactionDetail.Amount.ToString();

If transactionDetail is null, the code crashes.

How to Fix It

Always check for null before accessing properties:

C#
if (transactionDetail != null)
{
    var amount = transactionDetail.Amount.ToString();
}
else
{
    Console.WriteLine("Transaction details are missing.");
}

Use the null conditional operator (C# 8+):

C#
var amount = transactionDetail?.Amount?.ToString() ?? "N/A";

Use ?? throw for required values:

C#
var amount = transactionDetail?.Amount?.ToString() ?? throw new InvalidOperationException("Transaction details are required.");

2. SQL Exception: “Timeout expired. The timeout period elapsed prior to completion of the operation.”

This error is painful when you’re running complex queries that process large amounts of data, such as generating reports or fetching detailed records from a database. It means a SQL query took too long to execute.

How to Fix It

Optimize your SQL query

  • Use indexing to speed up searches.
  • Avoid SELECT *, only retrieve the columns you need.
  • Add a WHERE clause to reduce unnecessary data.

Increase the SQL Command Timeout in C#

C#
var command = new SqlCommand(query, connection);
command.CommandTimeout = 120; // 120 seconds

Use Asynchronous Calls to Prevent Freezing

C#
var result = await dbContext.Transactions.Where(t => t.Date >= startDate).ToListAsync();

3. HTTP 500 Internal Server Error (ASP.NET Core API)

You’re testing your API in Postman, expecting a nice JSON response, but instead, you get:

Plaintext
500 Internal Server Error

This means something broke in your API, but you’re not getting enough details.

How to Fix It

Enable Detailed Error Messages in Development Mode

In appsettings.Development.json, make sure detailed errors are enabled:

JSON
"Logging": {
  "LogLevel": {
    "Default": "Debug",
    "Microsoft": "Information"
  }
}

Use Try-Catch in Controllers

C#
[HttpGet]
public IActionResult GetTransactions()
{
    try
    {
        var transactions = _transactionService.GetAll();
        return Ok(transactions);
    }
    catch (Exception ex)
    {
        return StatusCode(500, new { message = "Something went wrong", error = ex.Message });
    }
}

Check API Logs

If you’re running your API in Docker, check logs using:

Bash
docker logs my-dotnet-api-container

4. CS0246: The type or namespace name ‘X’ could not be found

I ran into this when working with ClosedXML for generating Excel reports.

Why This Happens

How to Fix It

Check if the Namespace is Missing

C#
using ClosedXML.Excel;

Install the NuGet Package

Bash
dotnet add package ClosedXML

Ensure Your Project References the Correct Assembly

XML
<ProjectReference Include="..\SharedLibrary\SharedLibrary.csproj" />

5. CORS Policy Error in ASP.NET Core

You’re building a React/Angular frontend, but your API refuses to cooperate:

Plaintext
Access to fetch at 'https://api.example.com' from origin 'http://localhost:3000' has been blocked by CORS policy.
How to Fix It

Enable CORS in Startup.cs (for .NET 5 and earlier)

C#
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAll",
            builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
    });
}

public void Configure(IApplicationBuilder app)
{
    app.UseCors("AllowAll");
}

For .NET 6+ (Minimal API Approach)

C#
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseCors(policy => policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

app.MapGet("/", () => "Hello World!");

app.Run();

6. System.IO.FileNotFoundException: Could not load file or assembly

This one is a nightmare when deploying .NET applications. Your app crashes with a missing DLL error.

How to Fix It

Ensure the DLL Exists in the Deployment Folder

Check that the missing DLL is in your /bin folder.

Add the Required NuGet Package

Bash
dotnet add package Newtonsoft.Json

Use Assembly Binding Redirects (for older .NET Framework projects)

Add this to app.config or web.config:

XML
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

Errors in .NET can be frustrating, but once you understand how to fix them, they become valuable learning experiences. Many of the issues covered here have come up in real-world projects, and troubleshooting them has helped me improve as a developer.

If you’ve encountered any other tricky .NET errors, feel free to share them! I’d be happy to help.

Assi Arai
Assi Arai
Articles: 31