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

Possible to throw a 404 error within an ASP.Net 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.


A much better way is:

// Throws a 404 Not foundResponse.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


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