I have an action that takes in a string that is used to retrieve some data. If this string results in no data being returned (maybe because it has been deleted), I want to r
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");
}
I've used this:
Response.StatusCode = 404;
return null;
There are multiple ways to do it,
throw new HttpException(404, "Some description");
If you are working with .NET Core, you can return NotFound()
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>
Please try the following demo code:
public ActionResult Test()
{
return new HttpStatusCodeResult (404,"Not found");
}