In this article I will explain with an example, how to implement error logging and exception handling in ASP.Net Core (.Net Core) Razor Pages.
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 more details on ASP.Net Core (.Net Core) 7 Razor Pages, please refer my article ASP.Net Core 7 Razor Pages: Hello World Tutorial with Sample Program example.
 
 

Razor PageModel (Code-Behind)

The PageModel consists of following Handler methods.

Handler Method for handling GET operation

This Handler method left empty as it is not required.
 

Handler method for handling POST operation

Inside this Handler method, an exception is raised by converting a string value to integer inside a Try-Catch block and inside the Catch block and the LogError function is called.
Then, the raised Exception is caught in the Catch block and the LogError function is called.
Inside the LogError function, the ErrorLog Text file is accessed using IWebHostEnvironment interface.
Note: For more details on IWebHostEnvironment, please refer my article Using IWebHostEnvironment in ASP.Net Core.
 
Then, using the StreamWriter class object, the details of the exception (error) are written to an ErrorLog Text file along with current date and time.
Note:The second parameter is passed as TRUE to the StreamWriter class, so that the contents are appended to the Text file.
 
public class IndexModel : PageModel
{
    private IWebHostEnvironment Environment;
    public IndexModel(IWebHostEnvironment environment)
    {
        this.Environment= environment;
    }
 
    public void OnGet()
    {
    }
 
    public void OnPostRaiseException()
    {
        try
        {
            int i = int.Parse("Mudassar");
        }
        catch (Exception ex)
        {
            this.LogError(ex);
        }
    }
 
    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.WebRootPath, "ErrorLog\\ErrorLog.txt");
        using (StreamWriter writer = new StreamWriter(path, true))
        {
            writer.WriteLine(message);
            writer.Close();
        }
    }
}
 
 

Razor Page (HTML)

HTML Markup

Inside the Razor Page, the ASP.Net TagHelpers is inherited.
The Razor Page consists of an HTML Form with following ASP.Net TagHelpers attribute.
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.
The Submit Button has been set with the POST Handler method using the asp-page-handler attribute.
Note: In the Razor PageModel, the Handler method name is OnPostRaiseException but here it will be specified as RaiseException when calling from the Razor HTML Page.
 

Submitting the Form

When the Submit Button is clicked, the exception (error) are written to an Error Log Text file along with current date and time.
@page
@model Error_Log_File_ASP.Net_Razor.Pages.IndexModel
@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">
        <input type="submit" value="Raise Exception" asp-page-handler="RaiseException" />
    </form>
</body>
</html>
 
 

Screenshot

Error logging and Exception handling in ASP.Net Core Razor Pages
 
 

Downloads