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

Handling 404 not found in asp.net core mvc

Suggested Videos
Part 54 - Upload multiple files in asp.net core mvc | Text | Slides
Part 55 - Edit view in asp.net core mvc | Text | Slides
Part 56 - httppost edit action in asp.net core mvc | Text | Slides

In this video we will discuss
  • The 2 types of 404 errors in asp.net core mvc
  • How to handle 404 Not Found errors in asp.net core mvc

404 Errors in ASP.NET Core

There are 2 types of 404 errors.

Type 1 : Resource with the specified ID does not exit. This type of 404 errors occur when you cannot find the employee, product, customer etc with the provided ID.


Consider the following Details action method of HomeController

public ViewResult Details(int id)
{
    Employee employee = _employeeRepository.GetEmployee(id);

    if (employee == null)
    {
        Response.StatusCode = 404;
        return View("EmployeeNotFound", id);
    }

    return View(employee);
}

The following URL invokes the Details() action of the HomeController passing it the ID of 99

http://localhost/home/details/99

404 Not Found View Code

We are using Bootstrap 4 to apply styles to the view

@model int

@{
    ViewBag.Title = "404 Error";
}

<div class="alert alert-danger mt-1 mb-1">
    <h4>404 Not Found Error :</h4>
    <hr />
    <h5>
        Employee with ID = @Model cannot be found
    </h5>
</div>

<a asp-controller="home" asp-action="index" class="btn btn-outline-success"
   style="width:auto">Click here to see the list of all employees</a>

In this case, we know the user is trying to go to the employee details page, but the provided ID value is invalid. So we are returning a custom error page with the message, the ID cannot be found and a link that he could click to see the list of all employees.

handling 404 not found in asp.net core mvc

Type 2 : The URL does not match any route

Consider the following route. This also results in a 404 error

http://localhost/foo/bar

In this case we are not sure, the page the user is trying to get to so displaying a custom error page is not possible. In this case we want to return a generic error page. We will discuss how to do handle this type of 404 error in our next video.

asp.net core tutorial for beginners

2 comments:

  1. Hi Venkat, Its really helpful from many corners. Thank you for doing this.
    Also I noticed that Title is not being rendered.
    @{
    ViewBag.Title = "404 Error";
    }

    ReplyDelete
  2. Hi Venkat, I was wondering if there is a source repository for this series?

    ReplyDelete

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