by
back

Return 404 statuscode in asp.net but still render the content of the page

In asp.net you can configure the error handling in the web.config file.
There are three options you can choose between: Off Mode, On Mode and Remote only

Off Mode

When the error attribute is set to "Off", the default error page from asp.net is used for local or remote users.

On Mode

If you set the attribute to "On", ASP.NET uses the defined custom error page instead of the default error page. This applies to both local and remote users.

RemoteOnly

The default ASP.NET error page is shown only to local users. All remote users will get the custom error page.

web.config

<configuration>
   <system.web>
      <compilation targetFramework="4.0" />
      <customErrors mode="On" defaultRedirect="url" >
         <error statusCode="404" redirect="404.aspx" />
      </customErrors>
   </system.web>
</configuration>

Skip Redirect to Errorpage on Page-level

Sometimes you don't want to redirect to an error-page but render the requested page. A good example is a soldout item in an onlineshop. The correct statuscode for google would be 404, but you surely want to display the product to your visitors together with an note "sorry, soldout" instead of redirecting to a general 404-page.

If you have Response.StatusCode = 404; in your code behind file, then ASP.NET will redirect to your error page.

An easy and quick solution to avoid the redirect is to write

Response.TrySkipIisCustomErrors = true;
Response.StatusCode = 404;`

Then the correct 404 header get's returned but you can still see the dynamic content of the page.



comments powered by Disqus