How to return 404 Http status code from ASP.NET MVC Application?

ASP.NET MVC3 includes a new class HttpNotFoundResult in  System.Web.Mvc namespace.

HttpNotFoundResult: Instance of HttpNotFoundResult class indicates to client(browser) that the requested resource was not found. It returns a 404 HTTP status code to the client. Generally we return 404 status code if a requested webpage is not available. In case of MVC applications we return 404 status code is in terms of resources, for example we are searching for particular user profile in the portal, if the user profile is not found, we can return 404.

How to return 404 status code from a MVC application?

First way is to instantiate HttpNotFoundResult class and return the object.

public ActionResult Index()
{
var result = new HttpNotFoundResult();
return result;
}

Next alternative is to makes use of HttpNotFound() helper method of the Controller class which returns the HttpNotFoundResult instance.

public ActionResult Index()
{
return HttpNotFound();
}

we can return 404 along with custom status code description,using the overloded version of HttpNotFound(string statusDescription).

public ActionResult Index()
{
return HttpNotFound("can not find requested resource");
}
Sharavan Kumar Kasagoni

Shravan is working as Senior Development Engineer in Pramati Technologies, earlier he worked with Thomson Reuters. He is responsible for design and development of RESTful APIs, Single Page Web Applications. He is awarded as Microsoft Microsoft Most Valuable Professional for years 2016, 2015, 2014 2013 and 2012 from Microsoft. He also is a Microsoft Certified Professional for Programming in HTML5 with JavaScript and CSS3 Specialist. Programming is his passion. He is core member of Microsoft User Group Hyderabad. In his overall experience of 7+ years, his expertise includes Azure, C#, Swift, ASP.NET MVC, HTML 5, TypeScript, Object Oriented JavaScript, JavaScript Frameworks (Angular, Angular 2, Backbone, React), iOS. He also experiments on next generation JavaScript and Web technologies. Shravan's Blog: http://theshravan.net/blog Follow Shravan @ Twitter: @techieshravan