加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 22:15:32 所属栏目:asp.Net 来源:网络整理
导读:我已经尝试了以下2件事情让一个页面返回404错误: public ActionResult Index(){ return new HttpStatusCodeResult(404);}public ActionResult NotFound(){ return HttpNotFound();} 但它们都只是渲染一个空白页。如何手动从ASP.NET MVC 3中返回404错误? 解
我已经尝试了以下2件事情让一个页面返回404错误:
public ActionResult Index()
{
    return new HttpStatusCodeResult(404);
}

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

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

解决方法

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

你可以得到一个实际的视图显示,而不是通过添加一个customErrors元素到web.config中,当一个特定的状态代码发生时,你可以像处理任何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中添加一个路由条目,该路由条目将处理网址“404”,它会将请求传递到控制器的操作,该操作会显示404页面的视图。

Global.asax

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

CommonsController

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

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

有一个警告与上述方法:根据书“Pro ASP.NET 4在C#2010”(Apress)使用customErrors是过时的,如果你使用IIS 7.相反,你应该使用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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读