ASP.NET Core  

How to Troubleshoot Errors in a .NET MVC Website

Running a .NET MVC website in production can sometimes result in unexpected errors that affect performance, functionality, or user experience. Whether you encounter runtime exceptions, deployment failures, or configuration glitches, diagnosing and resolving errors effectively is a must-have skill for any ASP.NET MVC developer.

This article provides a step-by-step guide to troubleshoot errors in a .NET MVC application, covering the most common causes, tools, and best practices.

✅ Step 1: Enable Detailed Error Logs During Development

In development mode, allow detailed error messages to identify the issue quickly.

web.config

<system.web>
  <customErrors mode="Off"/>
  <compilation debug="true"/>
</system.web>
  • customErrors = Off shows full error details.

  • debug = true provides a stack trace.

⚠️ Do NOT enable these in production.

✅ Step 2: Check the Event Viewer Logs

If your MVC site is hosted on IIS, Windows Event Viewer is a great place to find exception logs.

  1. Open Event Viewer

  2. Navigate to Windows Logs > Application

  3. Look for .NET Runtime or Application Error

This helps identify runtime crashes and application pool failures.

✅ Step 3: Use Try-Catch and Global Error Handling

Catch unhandled errors globally using Application_Error in Global.asax or a custom filter.

Global.asax

protected void Application_Error()
{
    var exception = Server.GetLastError();
    // Log the exception
    System.Diagnostics.Trace.TraceError(exception.ToString());
}

Custom HandleErrorAttribute

public class CustomErrorHandler : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        // Log exception here
        base.OnException(filterContext);
    }
}

Register in FilterConfig.cs:

filters.Add(new CustomErrorHandler());

✅ Step 4: Check IIS Configuration and Permissions

Common IIS issues:

IssueSolution
HTTP 500 Internal Server ErrorCheck .NET version and pipeline mode
HTTP 404 Not FoundEnable MVC routing & extensionless URLs
Access Denied ErrorsGrant folder permissions to IIS_IUSRS
Application Pool Stopped AutomaticallyEnable "Always Running" and check logs

✅ Step 5: Debug Route Errors

Wrong URL routing can lead to 404 errors.

Use this debugging helper:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Also check:

  • Missing controllers/actions

  • Incorrect parameter names

  • Route conflicts

✅ Step 6: Troubleshoot Dependency and DLL Issues

Example runtime error:

Could not load file or assembly 'Newtonsoft.Json'

✅ Solutions:

  • Check bin folder for missing DLLs

  • Install via NuGet:

    Install-Package Newtonsoft.Json
    
  • Ensure Copy Local = true for references

✅ Step 7: Log Exceptions Using Logging Tools

Instead of relying on console logs, use structured logging:

  • NLog

  • Serilog

  • Elmah (popular for MVC)

Example with NLog:

private static readonly Logger logger = LogManager.GetCurrentClassLogger();

try
{
    // some logic
}
catch(Exception ex)
{
    logger.Error(ex);
}

✅ Step 8: Debug Using Browser Developer Tools

Use F12 Developer Tools for:

  • Network call failures (500/404 status)

  • JavaScript runtime errors

  • Invalid AJAX responses

  • Missing CSS/JS files

✅ Step 9: Use Remote Debugging (Advanced)

Attach Visual Studio debugger to the live IIS process:

  1. Install Remote Debugging Tools on the server

  2. From Visual Studio → Debug → Attach to Process

  3. Select w3wp.exe

Great for live issue reproduction.

✅ Step 10: Enable Friendly Error Pages in Production

Use custom error pages to show user-friendly messages.

<customErrors mode="On" defaultRedirect="~/Error">
  <error statusCode="404" redirect="~/Error/NotFound"/>
  <error statusCode="500" redirect="~/Error/ServerError"/>
</customErrors>

🔧 Common MVC Error Checklist

Error TypeQuick Fix
Configuration ErrorCheck web.config
Dependency DLL MissingReinstall NuGet package
Database Connection FailedTest connection string
Unauthorized Error (401/403)Check IIS authentication
NullReferenceExceptionValidate objects
View Not FoundVerify view name/path
Route Not MatchingFix RouteConfig

✅ Conclusion

Troubleshooting a .NET MVC application becomes much easier when you follow a systematic approach. Always:

✔ Enable logging
✔ Capture error details
✔ Check IIS & permissions
✔ Validate configuration
✔ Test routing and dependencies

With the right techniques, you’ll diagnose and resolve most issues quickly and professionally.

✅ How to pick the right tool

Here are some criteria and matching considerations:

  • Scope of monitoring: Are you just after error tracking + logs, or full performance/transactions tracing? Tools like Dynatrace or Retrace cover full APM; Sentry is more error-focused.

  • Deployment environment: On-premises, Azure, Cloud, hybrid? Azure Application Insights is strong for Azure.

  • Budget & complexity: Some tools are enterprise and can get expensive; simpler tools may suffice for smaller apps.

  • Instrumentation effort: Some tools require adding SDKs, configuration; some are more plug-and-play.

  • What you want to monitor: Web requests, database queries, dependencies (APIs/queues), user-experience (browser/client side)?

🛠 Practical tips for using these tools in your troubleshooting workflow

  • Instrument early in development/QA so you have telemetry before production issues.

  • Define key metrics: error rate, request latency, database query time, and slow controller actions.

  • Set up alerts: e.g., if error rate spikes or response times degrade.

  • Use the tool to trace back from symptom (slow page, error) to root cause (slow DB query, blocking thread, dependency failure).

  • Correlate logs + performance: e.g., an exception thrown during a long response, or a dependency (external API) lagging causing a bottleneck.

  • Use historical data: trending errors/performance over time helps catch gradual regressions.

  • Don’t just monitor server-side; if you have browser-client interactions (AJAX), track from the user side too.