asp.net-mvc-3 - 返回404错误ASP.NET MVC 3

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

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

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

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

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

最佳答案

如果您使用 fiddler 检查响应,我相信您会发现空白页面实际上返回了404状态代码。问题是没有渲染 View ,因此空白页。

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

首先在适当的地方扔HttpException。实例化异常时,请确保使用如下重载之一,该重载采用http状态代码作为参数,如下所示。

throw new HttpException(404, "NotFound");

然后在web.config文件中添加一个自定义错误处理程序,以便您可以确定在发生上述异常时应呈现哪种 View 。下面是一个示例:
<configuration>
    <system.web>
        <customErrors mode="On">
          <error statusCode="404" redirect="~/404"/>
        </customErrors>
    </system.web>
</configuration>

现在,在Global.asax中添加一个处理URL的路由条目“404”,它将请求传递给 Controller ​​的操作,该操作将显示404页面的 View 。

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

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

剩下的就是为上述操作添加 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.

关于asp.net-mvc-3 - 返回404错误ASP.NET MVC 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5635114/

相关文章:

c# - 删除.net mvc中的路由元素

jquery - 使用防伪 token 将 JSON 模型发布到 ASP.Net MVC3

asp.net - 无法从 'System.Web.Mvc.ModelStateDictionary' 转换为 'Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary'

php - 使用 .htaccess 和国家/地区位置(在网站 url 中)重定向到自定义 404 页面

python - urllib2错误 'Not found on Accelerator'

php - Magento 自定义路由/ Controller 转到 404

asp.net-mvc-3 - 将 WebForms 与现有的大型自定义控件库集成/切换到 MVC3

c# - ASP.NET MVC 3.0 图表助手显示图例

tomcat 5.0.9 在无法访问服务器的情况下覆盖 404 错误页面声明 - 需要自定义 404 消息

Eclipse:无法像在 Netbean 上那样运行 servlet:HTTP 状态 404