ASP.Net Core 7.0 Web App (Model-View-Controller) ErrorViewModel OnGet OnPost do not get called or executed

37 Views Asked by At

I've been struggling with setting up global error handling for my ASP.Net Core MVC Web App. I've been trying to apply the following article and I've had no luck.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-7.0

Running the app with IIS Express in debug.

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 thisIsDumb = "dumb";
        }

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.

0

There are 0 best solutions below