MYBLOG

欢迎来到小马哥的个人博客~

[原创]关于.net 设置404页面的说明

2020-03-08学海无涯

什么是404页面?

404页面指的是原来可以正常访问的链接,在某些特殊的原因后失效,在访问这个链接的时候,服务器就会返回404状态的错误页面。

那么如何设置404页面呢?本文将针对ASP.NET设置404页面进行说明

1、当页面打开某条信息,但是这条信息在数据库中查询不到时?如何正确跳转404页面呢?

  必须保证打开此页面时,页面返回404状态码,而不是简简单单的跳转404页面就完事了,设置代码如下(Server.Transfer 和 Response.Redirect 用法区别

  

        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.StatusCode = 404;
        HttpContext.Current.Response.Status = "404 Moved Premanet";
        HttpContext.Current.Server.Transfer("~/404.aspx");

2、如何通过webconfig设置404页面呢?(customErrors与httpErrors的区别


<system.web>
    <customErrors mode="On" defaultRedirect="/404.html">
        <error statusCode="403" redirect="/404.html" />
        <error statusCode="404" redirect="/404.html" />
        <error statusCode="500" redirect="/404.html" />
    </customErrors>
</system.web>
<system.webServer>
  <httpErrors errorMode="Custom" existingResponse="Auto" defaultResponseMode="ExecuteURL" >
    <remove statusCode="403"/>
    <remove statusCode="404"/>
    <remove statusCode="500"/>
    <error statusCode="403" responseMode="ExecuteURL" path="/404.aspx" />
    <error statusCode="404" responseMode="ExecuteURL" path="/404.aspx" />
    <error statusCode="500" responseMode="ExecuteURL" path="/404.aspx" />
  </httpErrors>
</system.webServer>
3、那么404页面要如何进行设置呢?



        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.StatusCode = 404;
        HttpContext.Current.Response.Status = "404 Moved Premanet";
4、设置完毕之后再打开站长之家状态码检测,测试下,返回码是否为404