I'm trying to follow the following article in order to implement global error handling and a custom error page for my web site.
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-7.0
Running the app with IIS Express in debug.
Because I've struggled with this so much, I've started a new ASP.Net Core 7.0 Web App (Model-View-Controller) project. The setup is, at this point, I'm simply creating a new Web App project. Specifically, ASP.Net Core 7.0 Web App (Model-View-Controller). The only code I've changed from what you get by default when creating a new project is the following.
Program.cs
// Configure the HTTP request pipeline.
//if (!app.Environment.IsDevelopment())
//{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
//}
Controllers/HomeController.cs
//added HttpGet attribute to main index action.
[HttpGet]
public IActionResult Index()
{
//throw an application exception to test error handling
throw new ApplicationException("This is an error");
return View();
}
Models/ErrorViewModel.cs
//Added class attributes and PageModel inheritance
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
[IgnoreAntiforgeryToken]
public class ErrorViewModel : PageModel
public string? RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
//added OnGet method
public void OnGet()
{
string thisIsntWorking= "please work";
}
Shared/Error.cshtml - No change. If I add @page to the top, it breaks the ViewData["Title"] usage, i.e. ViewData["Title"] = "Error" doesn't work any more. ViewData becomes null.
I feel like this should be more straight forward but I'm clearly missing something. What I'm trying to do is get whatever unhandled exception occurs in my Web App to populate to an Error Detail Web Page. I'd really like some global error handling, but I just can't seem to get the basic OnGet OnPost to work in the model and I don't know how to trickle any form of exception to the ErrorViewModel for usage by a view.