In this article I will explain with an example, how to implement error logging and exception handling in ASP.Net Core.
The errors and exceptions will be written to a Text file as it is easier to find the cause of the error as the Error Log Text file can be easily opened using the basic Notepad application in Windows.
Note: For beginners in ASP.Net Core 7, please refer my article ASP.Net Core 7: Hello World Tutorial with Sample Program example.
 
 

Controller

The Controller consists of following Action methods.

Action method for handling GET operation

Inside this Action method, simply the View is returned.
 

Action method for handling POST operation

Inside this Action method, an exception is raised by converting a string value to integer inside a Try-Catch block.
Then, the raised Exception is caught in the Catch block and the LogError function is called.
Inside the LogError function, the ErrorLog Text file path is referenced using IWebHostEnvironment and StreamWriter class object is created where we pass the path of file.
Note: For more details on IWebHostEnvironment, please refer my article Using IWebHostEnvironment in ASP.Net Core.
 
Finally, using the StreamWriter class object, the details of the exception (error) are written to the ErrorLog Text file along with current date and time.
public class HomeController : Controller
{
    private IWebHostEnvironment Environment;
    public HomeController(IWebHostEnvironment _environment)
    {
        this.Environment = _environment;
    }
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public IActionResult RaiseException()
    {
        try
        {
            int i = int.Parse("Mudassar");
        }
        catch (Exception ex)
        {
            this.LogError(ex);
        }
        return View("Index");
    }
 
    private void LogError(Exception ex)
    {
        string message = string.Format("Time: {0}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
        message += System.Environment.NewLine;
        message += "-----------------------------------------------------------";
        message += System.Environment.NewLine;
        message += string.Format("Message: {0}", ex.Message);
        message += System.Environment.NewLine;
        message += string.Format("StackTrace: {0}", ex.StackTrace);
        message += System.Environment.NewLine;
        message += string.Format("Source: {0}", ex.Source);
        message += System.Environment.NewLine;
        message += string.Format("TargetSite: {0}", ex.TargetSite.ToString());
        message += System.Environment.NewLine;
        message += "-----------------------------------------------------------";
        message += System.Environment.NewLine;
        string path = Path.Combine(this.Environment.WebtRootPath, "ErrorLog\\ErrorLog.txt");
        using (StreamWriter writer = new StreamWriter(path, true))
        {
            writer.WriteLine(message);
            writer.Close();
        }
    }
}
 
 

View

The View consists of an HTML Form with following ASP.Net Tag Helpers attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of a Submit Button.
When the Submit Button is clicked, the exception (error) are written to the ErrorLog Text file along with current date and time.
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <form method="post" asp-controller="Home" asp-action="RaiseException">
        <input type="submit" value="Submit" />
    </form>
</body>
</html>
 
 

Screenshot

Error logging and Exception handling in ASP.Net Core
 
 

Downloads