在asp.net mvc 中,action方法里根据参数获取数据,假如获取的数据为空,为了响应404错误页,咱们能够return HttpNotFound(); 可是在asp.net webform中,实现方式就不同了。html
为了体现本人在实现过程当中的所遇到的问题,现举例来讲明。web
1. 在asp.net webform 中,新建一个WebForm1.aspx文件,WebForm1.aspx代码以下:mvc
<%@ 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>
浏览时会显示以下的效果:asp.net
如今须要实现传参id,若是id=3时获取不到数据,响应404工具
WebForm1.aspx.cs文件以下:ui
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 == "3") { Response.StatusCode = 404; HttpContext.Current.ApplicationInstance.CompleteRequest(); } } } }
访问以后发现,仍是显示了文字“当你看到这行文字时,表示访问正常!”,而开发人员工具中监视的响应状态码是404。spa
这不是我想要的效果,我想要的效果以下(相似访问一个不存在的资源时响应的404错误页):.net
该问题困扰了我好久,甚至有查找过资料是经过配置Web.Config自定义成错误页去实现,可是与我想要的效果不一致,我想要的效果是响应默认的IIS (或IISExpress)中的404错误页。code
某天也是在找该问题的解决方案,不经意间找到了解决方法:orm
Response.StatusCode = 404; 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 == "3") { Response.StatusCode = 404; Response.SuppressContent = true; HttpContext.Current.ApplicationInstance.CompleteRequest(); } } } }
编译,再次访问,效果以下: