在asp.net mvc 中,action方法里根据参数获取数据,假如获取的数据为空,为了响应404错误页,我们可以return HttpNotFound(); 但是在asp.net webform中,实现方式就不一样了。

为了体现本人在实现过程中的所遇到的问题,现举例来说明。

1. 在asp.net webform 中,新建一个WebForm1.aspx文件,WebForm1.aspx代码如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="PageNotFoundDemo.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
当你看到这行文字时,表示访问正常!
</body>
</html>

浏览时会显示如下的效果:

现在需要实现传参id,如果id=3时获取不到数据,响应404

WebForm1.aspx.cs文件如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; namespace PageNotFoundDemo
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string id = Request.QueryString["Id"];
if (id == "")
{
Response.StatusCode = ;
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
}
}

访问之后发现,还是显示了文字“当你看到这行文字时,表示访问正常!”,而开发人员工具中监视的响应状态码是404。

这不是我想要的效果,我想要的效果如下(类似访问一个不存在的资源时响应的404错误页):

该问题困扰了我很久,甚至有查找过资料是通过配置Web.Config自定义成错误页去实现,但是与我想要的效果不一致,我想要的效果是响应默认的IIS (或IISExpress)中的404错误页。

某天也是在找该问题的解决方案,不经意间找到了解决方法:

Response.StatusCode = ;
Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();

Response.SuppressContent的解释如下:

修改后webform1.aspx.cs的代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; namespace PageNotFoundDemo
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string id = Request.QueryString["Id"];
if (id == "")
{
Response.StatusCode = ;
Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
}
}

编译,再次访问,效果如下:

最新文章

  1. hibernate多对多关联映射
  2. Linux 利用 locate 和 find 查找文件
  3. Leetcode Construct Binary Tree from Preorder and Inorder Traversal
  4. 1076 K尾相等数
  5. Java Topology Suite (JTS)与空间数据模型
  6. linux 获取系统屏幕分辨率
  7. Android 之 自定义标签 和 自定义组件
  8. MySQL教程及经常使用命令1.1
  9. Omi应用md2site-0.5.0发布-支持动态markdown拉取解析
  10. 本地计算机上的OracleOraDb10g_home1TNSListener服务启动后又停止了..........解决办法
  11. class A&lt;T&gt; where T:new()
  12. 自定义注解(spring)
  13. js 大厦之JavaScript事件
  14. echarts中dataZoom的使用
  15. 论文阅读笔记:【Transforming Auto-encoders】
  16. Mac OS X系统 用dd命令将iso镜像写入u盘
  17. Oracle数据库查询基本数据
  18. android.view.WindowManager$BadTokenException: Unable to add window
  19. 一个查表置换的CM
  20. 洛谷P4135 作诗

热门文章

  1. linux中一些简便的命令之cut
  2. python 打包exe
  3. Android中为什么需要服务?
  4. 从零开始学 Web 之 CSS3(六)动画animation,Web字体
  5. 解决 &quot;Script Error&quot; 的另类思路
  6. ruby执行字符串代码
  7. Java与c#的一些细节区别
  8. Hyperledger Fabric密码模块系列之BCCSP(四)
  9. 弱引用(WeakReference)
  10. Java字符串String