Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to throw a 404 error within an ASP.Net page?

I was wondering if it's possible to throw a 404 error from within a page(code behind)? Or possibly even throw any other type of error page such as 408(timeout) or 401(authentication required)?

Note: I don't just want to have the page return a status code of 404, I want it to use the ASP.Net(or my CustomErrors) 404 error page.

Something like this in the code behind:

if(id>10){ //if id is greater than 10, then it doesn't exist here   throw 404Error(); } 
like image 504
Earlz Avatar asked Feb 11 '11 22:02

Earlz


People also ask

How do you throw a 404 error?

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.

When should you throw a 404 error?

404 error codes are generated when a user attempts to access a webpage that does not exist, has been moved, or has a dead or broken link. The 404 error code is one of the most frequent errors a web user encounters. Servers are required to respond to client requests, such as when a user attempts to visit a webpage.

How does global ASAX handle 404 error?

StatusCode = 404; Response. StatusDescription = "Page not found"; You can also handle the various other error codes in here quite nicely. Google will generally follow the 302, and then honour the 404 status code - so you need to make sure that you return that on your error page.


1 Answers

You could throw an HttpException and set the corresponding status code:

throw new HttpException(404, "Not found"); 

It will also work with other status codes. Just a remark about the 401: as you probably know when ASP.NET MVC detects this code it automatically redirects you to the login page and getting a custom error page for the 401 status code could be a real PITA to implement.

like image 97
Darin Dimitrov Avatar answered Sep 22 '22 15:09

Darin Dimitrov