在ASP.NET页面的代码隐藏类中响应IIS的标准404 Not Found页面

问题描述

| 我希望能够生成IIS的标准404响应,而不是自定义404页面,以响应代码隐藏类中的错误情况。我的
Page_Load
方法看起来像这样:
protected void Page_Load(object sender,System.EventArgs e)
{
    this.a = ...
    ...
    if (this.a == null) ... // *** generate a 404
}
因此,如果
a
不为null,则呈现
.aspx
文件,以此类推,但是如果
a
为null,我希望显示标准的“找不到资源”页面,并带有404响应代码。 如果我使用:
if (a == null) Response.StatusCode = 404;
(根据我所发现的,这似乎是正确的方法)页面继续呈现(并在尝试使用
a
时给出
NullReferenceException
的响应码为500)。 如果我使用:
if (a == null) throw new HttpException(404,\"Not found\");
响应代码为404,但页面内容为ASP.NET未处理的异常页面,显示HttpException(当
customErrors
On
时,将显示为通用\“ Runtime Error \”)。 我想显示IIS的404页面,因为用户会理解这一点,但是如果页面显示服务器错误,他们可能不会检查该页面的响应代码。 编辑:看来我不能完全做到这一点。给定@ Smudge202的答案,我让我的代码背后投掷
HttpException
,并将代码添加到
Global.Application_Error()
以处理这些异常:
void Application_Error(object sender,EventArgs e)
{
var exception = Server.GetLastError();

    if (exception is HttpException)
    {
        var httpException = (HttpException)exception;
        if (httpException.GetHttpCode() == 404)
        {
            var context = HttpContext.Current;
            context.Response.Clear();
            context.Response.StatusCode = 404;
            context.Response.StatusDescription = \"Not Found\";
            context.Response.Write(\"<h1>404 Not Found</h1>\");
            context.Server.ClearError();
        }
    }
    // ...
}
这使我可以对异常设置自己的响应。这种方法有两个缺点: 我真正想做的是将控制权还原到IIS,并让其显示其默认的404响应,但我找不到解决方法 将为每个404显示新的响应(由
context.Response.Write()
编写),而不仅仅是代码中生成的响应 因此,看起来我将需要: 从后面的代码中,重定向到一个定制页面,该页面说明找不到“ thing”(这也设置了404响应代码),或者 设置自定义全局404页面     

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)