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(); }
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.
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.
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.
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.
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