zoukankan      html  css  js  c++  java
  • asp.net根据参数找不到记录后响应404及显示错误页

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

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

     

  • 相关阅读:
    NLP Best Practices
    Bert模型精简方法
    delphi:对象的创建(create)与释放(free/destory)(转载)
    delphi:Format格式化函数(转载)
    delphi:destroy, free, freeAndNil, release用法和区别(转载)
    delphi:function ParamStr(i:LongInt):string
    jquery:上传文件
    bootstrapValidator中用ajax校验
    jquery中实时监控文本框的变化
    jquery判断checkbox是否选中
  • 原文地址:https://www.cnblogs.com/godbell/p/9961122.html
Copyright © 2011-2022 走看看