NOTE:- DeveloperExceptionPage middleware must be used only on the Development environment. Using this page on a non-development environment is a security risk as it contains detailed exception information that could be used by an attacker. Also, this exception page does not make any sense to the end-user.
Exception Handling in ASP.NET Core
On local development machine to simulate running the application on production environment set ASPNETCORE_ENVIRONMENT variable to Production.
"ASPNETCORE_ENVIRONMENT": "Production"
Step 1: For a non-development environment, add the Exception Handling Middleware to the request processing pipeline using UseExceptionHandler() method in the Configure() method of the Startup class.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
}
Step 2: Implement the ErrorController that retrieves the exception details and returns the custom Error view. In a production application, do not display the exception details on the error view. Log them to a database table, file, event viewer etc,
Please note : IExceptionHandlerPathFeature is in Microsoft.AspNetCore.Diagnostics namespace.
public class ErrorController : Controller
{
[AllowAnonymous]
[Route("Error")]
public IActionResult Error()
{
// Retrieve the exception Details
var exceptionHandlerPathFeature =
HttpContext.Features.Get<IExceptionHandlerPathFeature>();
ViewBag.ExceptionPath = exceptionHandlerPathFeature.Path;
ViewBag.ExceptionMessage = exceptionHandlerPathFeature.Error.Message;
ViewBag.StackTrace = exceptionHandlerPathFeature.Error.StackTrace;
return View("Error");
}
}
Logging exceptions in ASP.NET Core
We will have different logging method with .NET Core as follows
ASP.NET Core built-in logging providers
- Console, Debug, EventSource, EventLog, TraceSource, AzureAppServicesFile , AzureAppServicesBlob, ApplicationInsights
- NLog, elmah, Serilog, Sentry, Gelf, JSNLog, KissLog.net, Loggr, Stackdriver
CreateDefaultBuilder() will also configures logging, adds the following 3 logging providers by default. This is the reason when we run the asp.net core project we see the log displayed both on the console and on the debug window in Visual Studio.
- Console
- Debug
- EventSource
CreateDefaultBuilder() method looks for Logging section in the application configuration file appsettings.json. LogLevel is used to control how much log data is logged or displayed.
Exception Logging Sample
public class ErrorController : Controller { private readonly ILogger<ErrorController> logger;
// Inject ASP.NET Core ILogger service. Specify the Controller // Type as the generic parameter. This helps us identify later which class or controller has logged the exception public ErrorController(ILogger<ErrorController> logger) { this.logger = logger; }
public IActionResult Error() { // Retrieve the exception Details var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>(); // LogError() method logs the exception under Error category in the log logger.LogError($"The path {exceptionHandlerPathFeature.Path} " + $"threw an exception {exceptionHandlerPathFeature.Error}");
return View("Error"); }}
public class ErrorController : Controller
{
private readonly ILogger<ErrorController> logger;
// Inject ASP.NET Core ILogger service. Specify the Controller
// Type as the generic parameter. This helps us identify later which class or controller has logged the exception
public ErrorController(ILogger<ErrorController> logger)
{
this.logger = logger;
}
public IActionResult Error()
{
// Retrieve the exception Details
var exceptionHandlerPathFeature =
HttpContext.Features.Get<IExceptionHandlerPathFeature>();
// LogError() method logs the exception under Error category in the log
logger.LogError($"The path {exceptionHandlerPathFeature.Path} " +
$"threw an exception {exceptionHandlerPathFeature.Error}");
return View("Error");
}
}
Logging to file in asp.net core using nlog
If you want only NLog as the logging provider, clear all the logging providers and then add NLog.
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{
// Remove all the default logging providers
logging.ClearProviders();
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
// Add NLog as the Logging Provider
logging.AddNLog();
})
.UseStartup<Startup>();
}
Comments
Post a Comment