Reputation: 63815
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();
}
Upvotes: 29
Views: 34779
Reputation: 29669
If your client is capable of hitting the PHP page so code is executed, it means that you didn't get a 404 (client side error, "path/file not found"), nor did you get any other sort of 400-class error, BUT you are instead actually getting what should be classified as a 500 error of some sort.
The HTTP spec uses file/path as synonyms. This comes from the old days of the internet when it was super common for webservers to expose directory browsing lists.
Upvotes: 0
Reputation: 16569
A much better way is:
// Throws a 404 Not found
Response.Clear();
Response.StatusCode = 404;
Response.End();
There is no need to throw an exception and the above works much better when using custom error pages in the Web.Config
Upvotes: 26
Reputation: 179
In regards of Page Load in ASP.NET WebForms needs some small workaround.
protected void Page_Load(object sender, EventArgs e)
{
HttpNotFound();
}
private void HttpNotFound()
{
Response.Clear();
Response.StatusCode = 404;
Response.End();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
Upvotes: 3
Reputation: 1038720
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.
Upvotes: 46