【问题标题】:Returning 404 Error ASP.NET MVC 3返回 404 错误 ASP.NET MVC 3
【发布时间】:2011-08-03 20:31:29
【问题描述】:

我尝试了以下 2 件事来让页面返回 404 错误:

public ActionResult Index()
{
    return new HttpStatusCodeResult(404);
}

public ActionResult NotFound()
{
    return HttpNotFound();
}

但它们都只是呈现一个空白页面。如何从 ASP.NET MVC 3 中手动返回 404 错误?

【问题讨论】:

    标签: asp.net-mvc-3 http-status-code-404


    【解决方案1】:

    如果您使用 fiddler 检查响应,我相信您会发现空白页实际上返回的是 404 状态码。问题是没有视图被呈现,因此是空白页。

    您可以通过在 web.config 中添加 customErrors 元素来显示实际视图,该元素将在出现特定状态代码时将用户重定向到特定 url,然后您可以像处理任何 url 一样处理。下面是一个演练:

    在适用的情况下,首先抛出HttpException。实例化异常时,请务必使用将 http 状态代码作为参数的重载之一,如下所示。

    throw new HttpException(404, "NotFound");
    

    然后在您的 web.config 文件中添加一个自定义错误处理程序,以便您可以确定在发生上述异常时应该呈现什么视图。下面是一个例子:

    <configuration>
        <system.web>
            <customErrors mode="On">
              <error statusCode="404" redirect="~/404"/>
            </customErrors>
        </system.web>
    </configuration>
    

    现在在您的 Global.asax 中添加一个路由条目,该条目将处理 url “404”,它将请求传递给控制器​​的操作,该操作将显示您的 404 页面的视图。

    全球.asax

    routes.MapRoute(
        "404", 
        "404", 
        new { controller = "Commons", action = "HttpStatus404" }
    );
    

    CommonsController

    public ActionResult HttpStatus404()
    {
        return View();
    }
    

    剩下的就是为上述动作添加一个视图。

    对上述方法的一个警告:根据“Pro ASP.NET 4 in C# 2010”一书(Apress),如果您使用 IIS 7,则使用 customErrors 已过时。相反,您应该使用 @987654323 @ 部分。以下是书中的一段话:

    但尽管此设置仍然适用于 Visual Studio 的内置测试网站 服务器,它实际上已被 IIS 7.x 中的 &lt;httpErrors&gt; 部分取代。

    【讨论】:

    • 这对我有用,但我必须在控制器函数中添加 Response.StatusCode = 404; 才能不返回 200 状态以及 404 页面。
    【解决方案2】:

    我正在成功使用这个:

    return new HttpNotFoundResult();
    

    【讨论】:

      【解决方案3】:

      throw new HttpException(404, "NotFound");custom error handler 对我来说效果很好。

      【讨论】:

        【解决方案4】:

        你应该使用

        // returns 404 Not Found as EmptyResult() which is suitable for ajax calls
        return new HttpNotFoundResult();
        

        当您对控制器进行 AJAX 调用但未找到任何内容时。

        当您对控制器操作进行经典调用并返回视图时,您应该使用:

        // throwing new exception returns 404 and redirects to the view defined in web.config <customErrors> section
        throw new HttpException(404, ExceptionMessages.Error_404_ContentNotFound);
        

        【讨论】:

          【解决方案5】:

          您可以使用

          个性化 404 结果
          return new HttpStatusCodeResult(404, "My message");
          

          【讨论】:

            猜你喜欢
            • 2012-08-10
            • 1970-01-01
            • 2016-09-28
            • 1970-01-01
            • 1970-01-01
            • 2017-01-13
            • 2014-01-04
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多