返回404错误ASP.NET MVC 3

问题描述:

我曾尝试以下两件事情有一个页面返回404错误:返回404错误ASP.NET MVC 3

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

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

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

如果您使用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页面查看。

的Global.asax

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

CommonsController

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

所有剩下的就是添加一个视图上述操作。

上述方法的一个警告:根据“C#2010 Pro ASP.NET 4”(Apress)一书的说法,如果您使用IIS 7,则使用customErrors已过时。您应该使用httpErrors部分。下面是从书中报价:

But although this setting still works with Visual Studio’s built-in test web server, it’s effectively been replaced by the <httpErrors> section in IIS 7.x.

我成功地使用这样的:

return new HttpNotFoundResult(); 

throw new HttpException(404, "NotFound");custom error handler一起为我工作得很好。

可以个性化设置404结果与

return new HttpStatusCodeResult(404, "My message"); 
+1

是不是受到可怕的“404太短”的错误在IE浏览器? – 2012-08-14 02:53:31

当你正在AJAX调用你的控制器而你不应该使用

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

找到任何内容。

当你在进行经典调用控制器动作和返回次数,你应该使用:

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