简体   繁体   English

回应来自asp.net页面代码隐藏的404错误

[英]respond with 404 error from asp.net page codebehind

I have a scenario in which I'm serving a file from codebehind. 我有一个场景,我从代码隐藏服务文件

which file, depends on request. 哪个文件取决于请求。 in some cases there will be no file to serve and I want to return 404 to the browser. 在某些情况下,将没有要提供的文件,我想将404返回给浏览器。

how can I do that from codebehind? 我怎么能从代码隐藏中做到这一点? is this the correct course of action to show user there's no file available? 这是向用户显示没有可用文件的正确行动方案吗?

you can use the Response.StatusCode property to return a 404: 您可以使用Response.StatusCode属性返回404:

Page.Response.StatusCode = 404

As for the question of whether it's the "correct thing to do" I'd say it depends how the Page is going to be accessed. 至于它是否是“正确的事情”的问题,我会说这取决于如何访问Page。 If you're going to access it programmatically then yes I'd go with the 404. If however it is going to be a user facing system, then I'd go with a custom page of some sort. 如果您要以编程方式访问它,那么是的,我会选择404.如果它将成为面向用户的系统,那么我将使用某种自定义页面。 Programs like codes and humans like more understandable things :-) 代码和人类之类的程序比较容易理解:-)

throw new HttpException(404, "File not found");

I'd be more inclined to redirect them to a custom error page that clearly indicates that the file cannot be found, in the style of the rest of your web application. 我更倾向于将它们重定向到一个自定义错误页面,该页面清楚地表明无法找到该文件,这与Web应用程序的其余部分相似。

You can specify how to handle certain errors in web.config 您可以指定如何处理web.config中的某些错误

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM