Asp net custom error page

How to add custom error pages that properly handle 404s and exceptions in production with ASP.NET MVC Core.

Just recently I realized this blog had a small issue.
While there was a custom error page for 404s, it was done with a redirect, and the view was returned with a 200 OK.
This meant that in my telemetry, I would see the PageNotFound entries, but not what page they tried to access.

So I set out to fix this issue along with some other related things.
This is how I implemented custom error pages for 404s and exceptions on this blog.

Custom error pages

So what is a custom error page?
It is a nice-looking view that is meant to be used when something goes wrong in a production environment.

In development you would use:

app.UseDeveloperExceptionPage();

Now when an exception occurs, you will see a view that describes what went wrong and where.

But it should not be used in production as it could lead to security problems.
Users might also consider your site less stable, and never visit again.

So we want to show them something that says something like:

Oops! Something went wrong. We are very sorry, please try again in a moment. If the error persists…

In case of a 404 status code, by default ASP.NET Core just returns a white page.

Instead we would like to show something like:

Hey that thing you tried to access does not exist. Please check the URL is correct.

Exception handler middleware

Let’s start by handling exceptions properly.

In our application pipeline configuration, we will add the exception handler middleware:

if(!env.IsDevelopment())
{
    app.UseExceptionHandler("/error/500");
}

So what does this middleware do?

Well, put simply it:

  1. Calls the next middleware with a try-catch block
  2. If an exception is caught, the next middleware is called again with the request path set to what you gave as an argument

This re-execution means the original URL is preserved in the browser.

The controller and action that is implemented looks like this:

[Route("error")]
public class ErrorController : Controller
{
    private readonly TelemetryClient _telemetryClient;

    public ErrorController(TelemetryClient telemetryClient)
    {
        _telemetryClient = telemetryClient;
    }

    [Route("500")]
    public IActionResult AppError()
    {
        var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
        _telemetryClient.TrackException(exceptionHandlerPathFeature.Error);
        _telemetryClient.TrackEvent("Error.ServerError", new Dictionary<string, string>
        {
            ["originalPath"] = exceptionHandlerPathFeature.Path,
            ["error"] = exceptionHandlerPathFeature.Error.Message
        });
        return View();
    }
}

I took a look at the source code of the exception handler middleware,
and found that it sets this IExceptionHandlerPathFeature on the context before re-executing the request.

Here we access it to get the relative URL the user tried to access and the exception that occurred.
We use Application Insights to track the exception.

The view is pretty simple:

@{
    ViewBag.Title = "Error occurred";
}

<h1>We have a problem</h1>

<p>Sorry, an error occurred while executing your request.</p>

Now when an exception is thrown:

  1. The exception is logged in Application Insights
  2. User gets a nice-looking view instead of a stack trace
  3. The original URL is preserved in the browser so the user can try to refresh
  4. The response comes back with a 500 status code so it is tracked as a failed request in Application Insights

Handling 404s

We also want to handle 404 status codes gracefully.

In this blog, it could happen because the URL did not map to a controller action.
Or it might have, but we could not find something in the database.

404s are handled with a small middleware that is placed before the MVC middleware:

app.Use(async (ctx, next) =>
{
    await next();

    if(ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted)
    {
        //Re-execute the request so the user gets the error page
        string originalPath = ctx.Request.Path.Value;
        ctx.Items["originalPath"] = originalPath;
        ctx.Request.Path = "/error/404";
        await next();
    }
});

Re-executing a request is not hard as you can see.
We just call await next(); again.

Here we grab the original URL and put it in the HttpContext.Items collection.

This is the action that then handles the error in the ErrorController introduced earlier:

[Route("404")]
public IActionResult PageNotFound()
{
    string originalPath = "unknown";
    if (HttpContext.Items.ContainsKey("originalPath"))
    {
        originalPath = HttpContext.Items["originalPath"] as string;
    }
    _telemetryClient.TrackEvent("Error.PageNotFound", new Dictionary<string, string>
    {
        ["originalPath"] = originalPath
    });
    return View();
}

We track the event with a custom event in Application Insights, and include the original URL in the properties.

The view is quite simple again:

@{
    ViewBag.Title = "404";
}

<h1>404 - Page not found</h1>

<p>Oops, better check that URL.</p>

Go ahead, try accessing this link to see how it looks like: Test 404.

If you open the browser DevTools, you can again see we get the right status code: 404.

And the original URL is preserved in the browser.

Conclusions

Thanks for reading!

Feel free to add a comment if you have questions or improvement suggestions.

Official error handling docs can be found here: docs.asp.net.

I have an ASP.Net website and I want to use a custom error page. I put the following code in my web.config

<customErrors mode="On" defaultRedirect="~/error.aspx">
    <error statusCode="404" redirect="~/error.aspx" />
</customErrors>

The problem is when i go to a URL that does not exist is still uses the 404 error page specified in IIS Manager.

Question: How can I make it use the error.aspx page I have created? Why do the settings in IIS Manager override the web.config?

Çağdaş Tekin's user avatar

Çağdaş Tekin

16.6k4 gold badges49 silver badges58 bronze badges

asked Jan 29, 2010 at 10:58

Yeodave's user avatar

1

Try this way, almost same.. but that’s what I did, and working.

<configuration>
    <system.web>
       <customErrors mode="On" defaultRedirect="apperror.aspx">
          <error statusCode="404" redirect="404.aspx" />
          <error statusCode="500" redirect="500.aspx" />
       </customErrors>
    </system.web>
</configuration> 

or try to change the 404 error page from IIS settings, if required urgently.

Alex Peta's user avatar

Alex Peta

1,3971 gold badge14 silver badges26 bronze badges

answered Jan 29, 2010 at 11:18

Hrushikesh's user avatar

HrushikeshHrushikesh

5733 silver badges12 bronze badges

2

There are 2 ways to configure custom error pages for ASP.NET sites:

  1. Internet Information Services (IIS) Manager (the GUI)
  2. web.config file

This article explains how to do each:

  • How To Set Up Custom Error Pages In IIS 7.5 With ASP.NET

The reason your error.aspx page is not displaying might be because you have an error in your web.config. Try this instead:

<configuration>
   <system.web>
      <customErrors defaultRedirect="error.aspx" mode="RemoteOnly">
         <error statusCode="404" redirect="error.aspx"/>
      </customErrors>
   </system.web>
</configuration>

You might need to make sure that Error Pages in IIS Manager — Feature Delegation is set to Read/Write:

IIS Manager: Feature Delegation panel

Also, this answer may help you configure the web.config file:

  • What is the difference between customErrors and httpErrors?

Community's user avatar

answered Aug 1, 2014 at 15:09

JohnB's user avatar

JohnBJohnB

17.6k16 gold badges97 silver badges110 bronze badges

1

<customErrors defaultRedirect="~/404.aspx" mode="On">
    <error statusCode="404" redirect="~/404.aspx"/>
</customErrors>

Code above is only for «Page Not Found Error-404» if file extension is known(.html,.aspx etc)

Beside it you also have set Customer Errors for extension not known or not correct as

.aspwx or .vivaldo. You have to add httperrors settings in web.config

<httpErrors  errorMode="Custom"> 
       <error statusCode="404" prefixLanguageFilePath="" path="/404.aspx"         responseMode="Redirect" />
</httpErrors>
<modules runAllManagedModulesForAllRequests="true"/>

it must be inside the <system.webServer> </system.webServer>

answered Jan 28, 2014 at 13:39

RASKOLNIKOV's user avatar

RASKOLNIKOVRASKOLNIKOV

7222 gold badges9 silver badges18 bronze badges

1

<system.webServer>     
<httpErrors errorMode="DetailedLocalOnly">
        <remove statusCode="404" subStatusCode="-1" />
        <error statusCode="404" prefixLanguageFilePath="" path="your page" responseMode="Redirect" />
    </httpErrors>
</system.webServer>

answered Apr 9, 2018 at 13:55

Tommaso's user avatar

TommasoTommaso

3114 silver badges7 bronze badges

1

Is it a spelling error in your closing tag ie:

</CustomErrors> instead of </CustomError>?

answered May 2, 2019 at 22:45

Siv's user avatar

SivSiv

852 silver badges12 bronze badges

Introduction

Structured exception handling is a fundamental part of the CLR and provides
.NET programmers with a great way of managing errors. In addition to the CLR
exception system, ASP.NET also provides ways of handling errors.

When a runtime or design-time error occurs in an application, ASP.NET shows a
default error page that gives a brief description of the error along with the
line number on which the error occurred. A developer would wish to view this
default error page, during the testing of the application since the description
helps him in rectifying the error. But he would never want a user trying to
access his application, to view this error page. The user would be least
bothered to know about the error. Instead of showing the default error page, it
would be more sensible to show a customized error page that would let the user
send notification of the error to the administrator.

Explanation

Consider an example of an ASP.NET application that generates an error
intentionally to show how ASP.NET detects it and shows the default error page.
The below given webform contains a label and a button server control. In the
eventhandler for the button click event, the user will be redirected to another
webform Trial.aspx. Since the page being redirected to is missing
ASP.NET it will show the default error page indicating it is a runtime error.

Unlike classic ASP, ASP.NET separates the code for the business logic from
the content (i.e. HTML and interface logic). The sample application has two
files named webform1.aspx containing the content and webform1.aspx.vb
containing the code.

WebForm1.aspx

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="webform1.aspx.vb" 
Inherits="ErrorSample.WebForm1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
    <HEAD>
        <title></title>
        <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
        <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
        <meta name="vs_defaultClientScript" content="JavaScript">
        <meta name="vs_targetSchema" 
            content="http://schemas.microsoft.com/intellisense/ie5">
    </HEAD>
    <body MS_POSITIONING="GridLayout">
        <form id="Form1" method="post" runat="server">
            <asp:Label id="Message" style="Z-INDEX: 101; LEFT: 34px; 
                POSITION: absolute; TOP: 46px" runat="server"></asp:Label>
            <asp:Button id="ErrorButton" style="Z-INDEX: 102; LEFT: 268px; 
                POSITION: absolute; TOP: 41px" runat="server" 
                Text="Generate Error"></asp:Button>
        </form>
    </body>
</HTML>

WebForm1.aspx.vb

Public Class WebForm1
    Inherits System.Web.UI.Page
    Protected WithEvents Message As System.Web.UI.WebControls.Label
    Protected WithEvents ErrorButton As System.Web.UI.WebControls.Button

    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)_
        Handles MyBase.Load
        Message.Text = "This sample page generates an Error..."
    End Sub

    Public Sub ErrorButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)_
        Handles ErrorButton.Click
        Response.Redirect("Trial.aspx")
    End Sub

End Class

Now if you try to run the above web form by viewing it on the browser, you
will get the below shown web page:

Image 1

Now if you click on the button labelled «Generate Error», you will get the
below shown default ASP.NET error page.

Image 2

Customizing Error Page

To customize the default error page, one will have to change the default
configuration settings of the application.

There are three error modes in which an ASP.NET application can work:

1) Off Mode
2) On Mode
3) RemoteOnly Mode

The Error mode attribute determines whether or not an ASP.NET error message
is displayed. By default, the mode value is set to «RemoteOnly».

Off Mode

When the error attribute is set to «Off», ASP.NET uses its default error page
for both local and remote users in case of an error.

On Mode

In case of «On» Mode, ASP.NET uses user-defined custom error page instead of
its default error page for both local and remote users. If a custom error page
is not specified, ASP.NET shows the error page describing how to enable remote
viewing of errors.

RemoteOnly

ASP.NET error page is shown only to local users. Remote requests will first
check the configuration settings for the custom error page or finally show an
IIS error.

Configuration File

Customisation of error page can be implemented by adding a value for an
attribute defaultRedirect in the <customErrors>
tag of the configuration file web.config. This file determines
configuration settings for the underlying application.

Off Mode

In this scenario, set the mode attribute value to «Off» as shown below:

Web.Config File

="1.0"="utf-8"
<configuration>
    <system.web>
         <customErrors mode="Off" />
    </system.web>
</configuration>

When the sample ASP.NET web page is viewed in the browser from the remote
machine, one gets the below shown default error page.

Image 3

The above example thus shows that, whether it is local or remote access,
ASP.NET error page is shown.

On Mode

In this scenario, set the mode attribute value to «On» as shown below:

Web.Config File

="1.0"="utf-8"
<configuration>
    <system.web>
         <customErrors defaultRedirect="error.htm" mode="On" />
    </system.web>
</configuration>

As shown in the configuration file, the «defaultRedirect» attribute has been
set to a user-defined page error.htm. The user-defined error page can be
an ASP.NET web page, classic ASP page or a simple HTML page.

For example, the contents of the user-defined error page error.htm can
be given as follows:

Error.htm

<HTML>
    <BODY>
        <b>We are very sorry for the inconvenience caused to you...<br> </b>
    </BODY>
</HTML>

When the sample ASP.NET web page is viewed in the browser from the
remote/local machine, one gets the below shown custom error page.

Image 4

RemoteOnly Mode

In this scenario, set the mode attribute value to «RemoteOnly» as shown
below:

Web.Config File

="1.0"="utf-8"
<configuration>
    <system.web>
         <customErrors defaultRedirect="error.htm" mode="RemoteOnly" />
    </system.web>
</configuration>

Since the defaultRedirect attribute has been set, if the page is
requested from a remote machine page is redirected to error.htm and if
the page is requested from the local machine the default error page is shown.

Notification of Error to the Administrator

In a practical web application, customisation of error pages is not the only
requirement. The error, if encountered, should be reported to the administrator
so that it can be rectified thus enabling subsequent requests to work properly
without any error.

Notification of the error can be sent to the administrator in one of the
following two ways:

1) Error can be registered as a log entry in the Windows Event Log on the
administrator’s machine
2) An Email can be sent to the administrator with a suitable error message

Writing to the Event Log

In ASP.NET, error can be handled programmatically by writing appropriate code
in the page-level error event, for errors on an individual page or in the
application-level error event for handling errors that may occur in any page of
the application.

Therefore, code for writing in the Event Log should be written in either of
the events, depending on the requirement of the application. To illustrate this
example, I have written the code in the application-level event with the error
mode set to «RemoteOnly» and the defaultRedirect attribute to error.htm.
The application-level error event should be included in the global file global.asax
within the same application folder.

The contents of the global file can be given as follows:

Writing Log Entry in the Event Log

Imports System.Web
Imports System.Web.SessionState
Imports System.Diagnostics

Public Class Global
    Inherits System.Web.HttpApplication

     Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)

        Dim ErrorDescription As String = Server.GetLastError.ToString

        
        Dim EventLogName As String = "ErrorSample"
        If (Not EventLog.SourceExists(EventLogName)) Then
            EventLog.CreateEventSource(EventLogName, EventLogName)
        End If

        
        Dim Log As New EventLog()
        Log.Source = EventLogName
        Log.WriteEntry(ErrorDescription, EventLogEntryType.Error)

    End Sub

End Class

Event Log support is provided in .NET through the namespace System.Diagnostics.
So, for the above code to work, it is very essential to add a reference to the
above-mentioned namespace in the project. In the event handler for
application-level error, a log named «ErrorSample» is created if it does not
exist in the Event Log. If it already exists, the error entry is added to the
existing list of events. After viewing the page on the browser from a remote
machine, the event will get listed in the Event Log on the administrator’s
machine as shown below:

Image 5

Description of the error can be viewed by selecting the appropriate event and
double clicking it.

Another form pops up as shown below:

Image 6

Sending an Email to the Administrator

To illustrate this example, I have written the code for sending an Email to
the administrator in the application-level error event. The contents of the
global file can be given as follows:

Imports System.Web
Imports System.Web.SessionState
Imports System.Web.Mail

Public Class Global
    Inherits System.Web.HttpApplication
 
    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)

        Dim mail As New MailMessage()
        Dim ErrorMessage = "The error description is as follows : " &_
            Server.GetLastError.ToString
        mail.To = "administrator@domain.com"
        mail.Subject = "Error in the Site"
        mail.Priority = MailPriority.High
        mail.BodyFormat = MailFormat.Text
        mail.Body = ErrorMessage
        SmtpMail.Send(mail)

    End Sub

End Class

In the above code, SMTP service is being used to send the mail across. SMTP
mail service support is provided in .NET through the namespace System.Web.Mail.
So, for the above code to work, it is very essential to add a reference to the
above-mentioned namespace in the project.

A BE in Computers, currently working with Syntel India Ltd. His skillsets include VB 6.0,ASP,ADO.He is currently working on VB.Net,C#,ADO.Net,ASP.NET.
You can contact him at amit_kukreja@syntelinc.com

This tutorial is part of series that covers error handling in ASP.NET. You can find additional information on:

* Errors And Exceptions In ASP.NET — covers different kinds of errors, try-catch blocks, introduces Exception object, throwing an exception and page_error procedure.
* Application Level Error Handling in ASP.NET — goes a level higher and explains handling of unhandled errors by using Application_Error procedure in Global.asax file, using of custom Http modules, sending notification e-mail to administrator, show different error pages based on roles and logging errors to text files, database or EventLog.

This tutorial deals with user experience when error occurs. When error is occurred on ASP.NET web application, user will get default error page (which is not so nice looking, also known as «Yellow screen of death»). This error page confuses average visitor who don’t know the meaning of «Runtime Error». Although developers like to know many details about an error, it is better to show more friendly error page to your users.

Web.config file contains a customErrors section inside <System.web>. By default, this section looks like this:

<customErrors
mode=«RemoteOnly« />

As you see, there is mode parameter inside customErrors tag which value is «RemoteOnly». This means that detailed messages will be shown only if site is accessed through a http://localhost. Site visitors, who access from external computers will see other, more general message, like in image bellow:

Default ASP.NET error message
Default ASP.NET error message

mode parameter can have three possible values:

RemoteOnly — this is default value, detailed messages are shown if you access through a localhost, and more general (default) error message to remote visitors.

On — default error message is shown to everyone. This could be a security problem since part of source code where error occurred is shown too.

Off — detailed error message is shown to everyone.

Default ASP.NET error message hides details about error, but still is not user friendly. Instead of this page, ASP.NET allows you to create your own error page. After custom error page is created, you need to add a reference to it in customErrors section by using a defaultRedirect parameter, like in code snippet bellow:

<customErrors
mode=«RemoteOnly» defaultRedirect=«~/DefaultErrorPage.htm« />

When error occured, ASP.NET runtime will redirect visitor to DefaultErrorPage.htm. On custom error page you can gently inform your visitors what happened and what they can do about it.

DefaultErrorPage.htm will display when any error occurs. Also, there is a possibility to show different custom error pages for different types of exceptions. We can do that by using <error > sub tag. In code sample bellow, specialized pages are shown for errors 404 (File Not Found) and error 403 (Forbidden).


<
customErrors
mode=«On»
defaultRedirect=«~/DefaultErrorPage.htm« >


  <
error

statusCode=«404« redirect=«~/FileNotFound.htm«/>


  <
error

statusCode=«403« redirect=«~/Forbidden.htm«/>

</customErrors>

How to set error page for every ASP.NET page

Custom pages configured in Web.config affect complete web site. It is possible also to set error page for every single ASP.NET page. We can do this by using @Page directive. Code could look like this:


<%
@
Page language=»C#» Codebehind=»SomePage.aspx.cs»
errorPage=»MyCustomErrorPage.htm»
AutoEventWireup=»false»%>

Http Error page codes

There are different Http codes that your web application could return. Some
errors are more often than others. You probably don’t need to cover all cases. It is ok to place custom error pages for the most common error codes and place default error page for the rest.

400 Bad Request

Request is not recognized by server because of errors in syntax. Request should
be changed with corrected syntax.

401 Not Authorized

This error happens when request doesn’t contain authentication or authorization
is refused because of bad credentials.

402 Payment Required

Not in use, it is just reserved for the future

403 Forbidden

Server refused to execute request, although it is in correct format. Server may
or may not provide information why request is refused.

404 Not Found

Server can not find resource requested in URI. This is very common error, you
should add custom error page for this code.

405 Method Not Allowed

There are different Http request methods, like POST, GET, HEAD, PUT, DELETE etc. that could be used by client. Web server can be configured to allow or disallow specific method. For example, if web site has static pages POST method could be disabled. There are many theoretical options but in reality this error usually occurs if POST method is not allowed.

406 Not Acceptable

Web client (browser or robot) could try to receive some data from web server. If that data are not acceptable web server will return this error. Error will not happen (or very rarely) when web browser request the page.

407 Proxy Authentication Required

This error could occur if web client accesses to web server through a proxy. If proxy authentication is required you must first login to proxy server and then navigate to wanted page. Because of that this error is similar to error 401 Not Authorized, except that here is problem with proxy authentication.

408 Request Timeout

If connection from web client and server is not established in some time period, which is defined on web server, then web server will drop connection and send error 408 Request Timeout. The reason could be usually temporarily problem with Internet connection or even to short time interval on web server.

409 Conflict

This error rarely occurs on web server. It means that web request from client is in conflict with some server or application rule on web server.

410 Gone

This error means that web server can’t find requested URL. But, as opposed to error 404 Not Found which says: «That page is not existing», 410 says something like: «The page was here but not anymore». Depending of configuration of web server, after some time period server will change error message to 404 Not Found.

411 Length Required

This error is rare when web client is browser. Web server expects Content-Length parameter included in web request.

412 Precondition Failed

This is also rare error, especially if client is web browser. Error occurs if Precondition parameter is not valid for web server.

413 Request Entity Too Large

This error occurs when web request is to large. This is also very rare error, especially when request is sent by web browser.

414 Request URI Too Long

Similar like error 413, error occurs if URL in the web request is too long. This limit is usually 2048 to 4096 characters. If requested URL is longer than server’s limit then this error is returned. 2048 characters is pretty much, so this error occurs rarely. If your web application produces this error, then it is possible that is something wrong with your URLs, especially if you build it dynamically with ASP.NET server side code.

415 Unsupported Media Type

This error occurs rarely, especially if request is sent by web browser. It could be three different reasons for this error. It is possible that requested media type doesn’t match media type specified in request, or because of incapability to handle current data for the resource, or it is not compatible with requested Http method.

416 Requested Range Not Satisfied

This is very rare error. Client request can contain Range parameter. This parameter represents expected size of resource requested. For example, if client asks for an image, and range is between 0 and 2000, then image should not be larger from 2000 bytes. If image is larger, this error is returned. However, web page hyperlinks usually don’t specify any Range value so this error rarely occurs.

417 Expectation Failed

This is also rare error, especially if client is web browser. There is Expect parameter of request, if this Expect is not satisfied Expectation error is returned.

500 Internal Server Error

This is very common error; client doesn’t know what the problem is. Server only tells that there is some problem on server side. But, on the server side are usually more information provided. If server hosts ASP.NET application, then this often means that there is an error in ASP.NET application. More details about error could be logged to EventLog, database or plain text files. To see how to get error details take a look at Application Level Error Handling In ASP.NET tutorial.

501 Not Implemented

This is rare error. It means that web server doesn’t support Http method used in request. Common Http methods are POST, GET, HEAD, TRACE etc. If some other method is used and web server can’t recognize it, this error will be returned.

502 Bad Gateway

This error occurs when server is working as gateway and need to proceed request to upstream web server. If upstream web server response is not correct, then first server will return this error. The reason for this error is often bad Internet connection some problem with firewall, or problem in communication between servers.

503 Service unavailable

This error means that server is temporally down, but that is planned, usually because a maintenance. Of course, it is not completely down because it can send 503 error :), but it is not working properly. Client should expect that system administrator is working on the server and server should be up again after problem is solved.

504 Gateway Timeout

Similar to error 502 Bad Gateway, there is problem somewhere between server and upstream web server. In this case, upstream web server takes too long to respond and first server returned this error. This could happen for example if your Internet connection is slow, or it is slow or overloaded communication in your local network.

505 HTTP Version Not Supported

Web server doesn’t support Http version used by web client. This should be very rare error. It could happen eventually if web client tries to access to some very old web server, which doesn’t support newer Http protocol version (before v. 1.x).

Show different error pages based on roles

By using of RemoteOnly value for customErrors mode parameter in Web.config you can get detailed messages when you access through a localhost and custom messages if you access remotely. This could be a problem, because sometime you need to access remotely to web application and still see detailed messages. If you have shared hosting than this is only option. Of course, you still don’t want to show error details to end users.

If you use some role based security architecture you can show detailed message to single logged user (you) or to all users that belong to some role, for example «Developers». On this way, developers logged in to web application will see detailed error messages and your users will still see just friendly custom notification.

To implement this idea we need to add some code to Application_Error procedure in Global.asax file. Code could look like this:

[ C# ]

void Application_Error(object sender, EventArgs e)
{
if(Context != null)
{
// Of course, you don’t need to use both conditions bellow
// If you want, you can use only your user name or only role name
if(Context.User.IsInRole(«Developers») ||
(Context.User.Identity.Name == «YourUserName») )
{
// Use Server.GetLastError to recieve current exception object
Exception CurrentException = Server.GetLastError();

// We need this line to avoid real error page
Server.ClearError();

// Clear current output
Response.Clear();

// Show error message as a title
Response.Write(«<h1>Error message: « + CurrentException.Message + «</h1>»);
// Show error details
Response.Write(«<p>Error details:</p>»);
Response.Write(CurrentException.ToString());
}
}
}

[ VB.NET ]

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
If Context IsNot Nothing Then
‘ Of course, you don’t need to use both conditions bellow
‘ If you want, you can use only your user name or only role name
If Context.User.IsInRole(«Developers») Or _
(Context.User.Identity.Name = «YourUserName») Then

‘ Use Server.GetLastError to recieve current exception object
Dim CurrentException As Exception = Server.GetLastError()

‘ We need this line to avoid real error page
Server.ClearError()

‘ Clear current output
Response.Clear()

‘ Show error message as a title
Response.Write(«<h1>Error message: « & _
CurrentException.Message & «</h1>»)
‘ Show error details
Response.Write(«<p>Error details:</p>»)
Response.Write(CurrentException.ToString())
End If
End If
End Sub

ASP.NET Custom Error Pages Remarks

By using custom error pages you can achieve more professional look for your ASP.NET web application. Although your visitors will not be happy if something is not working, it will be much better if you told them that something is wrong, but you are aware of that and you will correct it as soon as possible. That will connect you closer to your users. Errors are almost unavoidable, but your competence to deal with them makes difference.

I hope that you find this tutorial helpful. Happy programming!


Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |   Google


Chris Love

Last Updated — Thu Nov 23 2017

ASP.NET and Search Engine Optimization was really being dissed as a good platform for optimized sites. One of the complaints raised by the article was the way ASP.NET handles custom errors. The complaint centers around two status codes being generated, first a 302 or temporary redirect is sent. Then a 200 status code is sent for a successful request. This is actually the proper way to indicate the custom error page process and I will explain why.

The basic premise behind custom error pages in ASP.NET is you as the developer can designate a page to be rendered when an unhandled exception is thrown by a request. You can also designate specific or specialized error pages be displayed when a specific status code, 404 for example is raised. The 404 status code is served when a resource cannot be found by the server.

How to Designate a Custom Error Page

The first thing I do when defining a custom error page is add the page to the site. The error page generally will consist of a notice to the user that something when wrong and a little reassurance that we (meaning I) will fix it as soon as we can. This is configured in the web.config file in the customErrors section. This element has two attributes, defaultRedirect and mode. The defaultRedirect attribute specifies the page that is displayed when an unhandled exception bubbles up through the chain of events.

<

customErrorsdefaultRedirect=~/error.aspxmode=RemoteOnly/>

The mode attribute can be set to either On, Off or RemoteOnly. When set to On the custom error page is displayed both to remote computers and the local server computer. When it is set to Off no custom error page is displayed and the actual exception details a spewed onto the page for any visitor creating the exception. This is known as the Yellow Screen of Death because the text has a yellow background.

Yello Screen of Death

Finally RemoteOnly will only show the custom error page to remote users, but the actual exception messages to the local computer. This is very useful when you have access to the web server and are trying to track down a pesky bug.

Designating Custom Pages for Status Code Errors

One of the lesser known tricks with custom ASP.NET error pages is the ability to designate custom pages to be sent to the browser when specific status codes are generated. For example when a 404 or page not found status is generated this is an error. A 404 status code is sent in the response to the browser. In IIS you can designate a specific resource to be sent to the client or a generic 404 error will be displayed by the Browser.

ASP.NET allows you to designate custom pages for each status code. A status code is used to tell the web client about the request. A code of 200 means successful, 301 means permanently redirected, 404 means not found and 500 means there was an internal server error.

To add custom error pages for various status code you can add those to the customErrors element like this:

<

customErrorsdefaultRedirect=~/error.aspxmode=RemoteOnly>

<

errorstatusCode=403redirect=default.aspx/>

<

errorstatusCode=404redirect=default.aspx/>

</

customErrors>

Notice how I redirect the request to the home page for a page not found status. I do this as a catch all because I inherit many sites where the owners are not certain of what they actually have, or there are so many possible pages that it is a last ditched measure to get the visitor to something important on the site. If you set up your URL Rewriting engine properly you should be able to stop any of these types of things from happening.

Custom Error Handling in ASP.NET and Status Codes

So this leaves the final issue, the status codes that are sent up when a custom error page is generated in ASP.NET. The issues {insert name here} was having is a 302 status code is sent, followed by a 200 status code. Which is exactly how it should work! The 302 status code is a temporary redirect, so we are telling the client that for now this is where this page is going, but it should come back soon.

Yes we have an error, which should be handled very soon and this page will return to this location as expected, so please do not remove me from your index, cache or what have you.

Next a custom error page is successfully returned, hence the 200 or successful status code sent to the client. I keep saying client instead of browser because the real issue for Search Engine Optimization is what the search engine spiders actually process. In this case we tell them, oops I have an error so for the time being go here. That page is successfully processed and returned, just like we wanted.

So in summary, configuring custom error pages in ASP.NET is a pretty trivial task. The status codes generated by the custom error page process are correct and as expected. Once the error is corrected the search engines should revisit the page and get the proper content from the page, so a temporary redirect or 302 status code is the correct code to return.

Понравилась статья? Поделить с друзьями:
  • Asp net core return internal server error
  • Asp net core cors error
  • Asp net core 500 internal server error
  • Asp net core 403 error
  • Asp net application error