分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

asp.net根据参数找不到记录后响应404及显示错误页

发布时间:2023-09-06 02:22责任编辑:郭大石关键词:暂无标签

在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 == "3") ???????????{ ???????????????Response.StatusCode = 404; ??????????????????????????????????HttpContext.Current.ApplicationInstance.CompleteRequest(); ???????????} ???????} ???}}

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

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

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

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

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(); ???????????} ???????} ???}}

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

asp.net根据参数找不到记录后响应404及显示错误页

原文地址:https://www.cnblogs.com/godbell/p/9961122.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved