Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get MVC action to return 404

People also ask

How do I return a 404 controller?

How to return 404 status code from a MVC application. First way is to instantiate HttpNotFoundResult class and return the object. Next alternative is to makes use of HttpNotFound() helper method of the Controller class which returns the HttpNotFoundResult instance.

How do you throw a 404 exception?

Just throw HttpException: throw new HttpException(404, "Page you requested is not found"); ASP.NET run-time will catch the exception and will redirect to the custom 404.

What can I return from ActionResult in MVC?

ActionResult is a return type of a controller method in ASP.NET MVC. It help us to return models to views, other return value, and also redirect to another controller's action method. There are many derived ActionResult types in MVC that we use to return the result of a controller method to the view.


In ASP.NET MVC 3 and above you can return a HttpNotFoundResult from the controller.

return new HttpNotFoundResult("optional description");

There are multiple ways to do it,

  1. You are right in common aspx code it can be assigned in your specified way
  2. throw new HttpException(404, "Some description");

In MVC 4 and above you can use the built-in HttpNotFound helper methods:

if (notWhatIExpected)
{
    return HttpNotFound();
}

or

if (notWhatIExpected)
{
    return HttpNotFound("I did not find message goes here");
}

Code :

if (id == null)
{
  throw new HttpException(404, "Your error message");//RedirectTo NoFoundPage
}

Web.config

<customErrors mode="On">
  <error statusCode="404" redirect="/Home/NotFound" />
</customErrors>

If you are working with .NET Core, you can return NotFound()


I've used this:

Response.StatusCode = 404;
return null;

In NerdDinner eg. Try it

public ActionResult Details(int? id) {
    if (id == null) {
        return new FileNotFoundResult { Message = "No Dinner found due to invalid dinner id" };
    }
    ...
}