Reply 404 error from asp.net page codebehind

I have a script in which I serve a file from code.

whose file depends on the request. in some cases there will be no files for maintenance, and I want to return 404 to the browser.

how can i do this from codebehind? is this the correct course of action to show the user if there is an available file?

+6
source share
3 answers

you can use the Response.StatusCode property to return 404:

Page.Response.StatusCode = 404 

Regarding the question of whether this is the “right thing”, I would say that it depends on how the page is available. If you are going to access it programmatically, then yes, I would go with 404. If, however, it would be a system facing the user, then I would go with a kind of custom page. Programs such as codes and people, as more understandable things :-)

+10
source share
 throw new HttpException(404, "File not found"); 
+6
source share

I would be more inclined to redirect them to a custom error page, which clearly indicates that the file cannot be found in the style of the rest of your web application.

You can specify how to handle certain errors in web.config

 <customErrors mode="On"> <error statusCode="404" redirect="FileNotFound.aspx"/> </customErrors> 
0
source share

All Articles