返回404错误ASP.NET MVC 3

rya*_*zec 30 http-status-code-404 asp.net-mvc-3

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

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

public ActionResult NotFound()
{
    return HttpNotFound();
}
Run Code Online (Sandbox Code Playgroud)

但他们两个只是渲染一个空白页面.如何从ASP.NET MVC 3中手动返回404错误?

xTR*_*ANx 63

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

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

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

throw new HttpException(404, "NotFound");
Run Code Online (Sandbox Code Playgroud)

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

<configuration>
    <system.web>
        <customErrors mode="On">
          <error statusCode="404" redirect="~/404"/>
        </customErrors>
    </system.web>
</configuration>
Run Code Online (Sandbox Code Playgroud)

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

Global.asax中

routes.MapRoute(
    "404", 
    "404", 
    new { controller = "Commons", action = "HttpStatus404" }
);
Run Code Online (Sandbox Code Playgroud)

CommonsController

public ActionResult HttpStatus404()
{
    return View();
}
Run Code Online (Sandbox Code Playgroud)

剩下的就是为上面的操作添加一个视图.

使用上述方法的一个警告:根据"使用C#2010中的Pro ASP.NET 4"一书(Apress),如果您使用的是IIS 7 ,则customErrors的使用已过时.您应该使用httpErrors部分.这是本书的引用:

但是,尽管此设置仍适用于Visual Studio的内置测试Web服务器,但它实际上已被<httpErrors>IIS 7.x中的部分取代.


Mar*_*nHN 17

我成功地使用了这个:

return new HttpNotFoundResult();
Run Code Online (Sandbox Code Playgroud)


Dar*_*rov 15

throw new HttpException(404, "NotFound");以及自定义错误处理程序对我来说很好.


mar*_*are 6

你应该用

// returns 404 Not Found as EmptyResult() which is suitable for ajax calls
return new HttpNotFoundResult();
Run Code Online (Sandbox Code Playgroud)

当您对控制器进行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);
Run Code Online (Sandbox Code Playgroud)