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.
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.
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,
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" };
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With