ASP.NET MVC 3 introduces some new action results like HttpNotFoundResult that you can use to let browser know that resource was not found. In this posting I will show you how to use HttpNotFoundResult in real-world applications.
HttpNotFoundResult class and HttpNotFound() method
Let’s start with ASP.NET MVC 3 default application and let’s modify Index() method of Home controller so it returns HttpNotFoundResults for some path. Here is my code:
public ActionResult NotFound()
{
var result = new HttpNotFoundResult();
return result;
}
Now let’s run our application and point browser to address http://myserver/Home/NotFound. As you can expect then the result is empty result with HTTP status code 404.
There is also shortcut method in Controller class that does exactly the same work. This protected method is called HttpNoFound() and you can use it exactly same way as you used HttpNotFoundResult before.
public ActionResult NotFound()
{
return HttpNotFound();
}
If you like to provide your own status message with error 404 then you can do it in constructor of HttpNotFoundResult. Also you can provide status description parameter for HttpNotFound method as shown in following example.
public ActionResult NotFound()
{
return HttpNotFound("I cannot find this thing!");
}
Page not found
I promised to give you some real-world example too. Here is example about controller method that is invoked when visitor requests some page (/Page/something-very-interesting). I hope comments in code are enough to make this method easy to understand.
public ActionResult Page(string urlName)
{
// ask pages from context that was injected by controller factory
var page = (from p in _context.Pages
where p.UrlName == urlName
select p)
.FirstOrDefault();
// if page is null then it has never been there - say it's not found
if (page == null)
return HttpNotFound();
// page found - show details
return View(page);
}
You can use similar code also for other types of systems like e-commerce, blogs, forums etc.
Conclusion
HttpNotFoundResult class and HttpNotFound() method are easy ways how to let server and browser know that resource asked by visitor is not found. It is also important information for search engine spiders because they are able to correct their indexes based on that information.
View Comments (0)