Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Handling 404 error in razor pages project

Suggested Videos
Part 10 - Route parameters in asp.net core razor pages | Text | Slides
Part 11 - Route constraints in asp.net core | Text | Slides
Part 12 - ASP.NET core custom route constraint | Text | Slides

In this video we will discuss handling 404 errors in an asp.net core razor pages project.

Consider the following OnGet() action. 


public IActionResult OnGet(int id)
{
    Employee = employeeRepository.GetEmployee(id);

    if(Employee == null)
    {
        return RedirectToPage("/NotFound");
    }

    return Page();
}

  • If the employee with the specified ID is not found, the request is redirected to NotFound razor page using RedirectToPage() method.
  • OnGet() method return type is IActionResult, where as RedirectToPage() method returns RedirectToPageResult. This is OK because RedirectToPageResult implements IActionResult.
  • If the employee with the specified ID is found we want to re-render the same page. This is done by the Page() method. Page() method returns PageResult which also implements IActionResult interface.
  • Changing the return type of OnGet() action from void to IActionResult allows us to return different result types that implement IActionResult interface.
asp.net core iactionresult interface

NotFound razor page

@page
@{
    ViewData["Title"] = "NotFound";
}

<h1>The resource you are looking for cannot be found</h1>
<a asp-page="/Employees/Index" class="btn btn-primary">
    Click here to go back to Home
</a>

asp.net core razor pages tutorial

No comments:

Post a Comment

It would be great if you can help share these free resources