Lỗi error running app default activity not found
The Debug profile determines how to start debugging the application. You can right click on your Project Properties > navigate to “Debug” > create a debug profile by specifying various properties. Show
About the error message, please launch your VS2019 as administrator and create a new project to check if it persists or not. Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support. Handle errors in ASP.NET Core
In this articleBy Tom Dykstra This article covers common approaches to handling errors in ASP.NET Core web apps. See also Handle errors in ASP.NET Core web APIs and Handle errors in Minimal API apps. Developer exception pageThe Developer Exception Page displays detailed information about unhandled request exceptions. ASP.NET Core apps enable the developer exception page by default when both:
The developer exception page runs early in the middleware pipeline, so that it can catch unhandled exceptions thrown in middleware that follows. Detailed exception information shouldn't be displayed publicly when the app runs in the Production environment. For more information on configuring environments, see Use multiple environments in ASP.NET Core. The Developer Exception Page can include the following information about the exception and the request:
The Developer Exception Page isn't guaranteed to provide any information. Use Logging for complete error information. Exception handler pageTo configure a custom error handling page for the Production environment, call UseExceptionHandler. This exception handling middleware:
Warning If the alternate pipeline throws an exception of its own, Exception Handling Middleware rethrows the original exception. Since this middleware can re-execute the request pipeline:
In the following example, UseExceptionHandler adds the exception handling middleware in non-Development environments:
The Razor Pages app template provides an Error page (
9 action method and an Error view for the Home controller. The exception handling middleware re-executes the request using the original HTTP method. If an error handler endpoint is restricted to a specific set of HTTP methods, it runs only for those HTTP methods. For example, an MVC controller action that uses the
00 attribute runs only for GET requests. To ensure that all requests reach the custom error handling page, don't restrict them to a specific set of HTTP methods. To handle exceptions differently based on the original HTTP method:
To allow unauthenticated users to view the custom error handling page, ensure that it supports anonymous access. Access the exceptionUse IExceptionHandlerPathFeature to access the exception and the original request path in an error handler. The following example uses
05 to get more information about the exception that was thrown:
Warning Do not serve sensitive error information to clients. Serving errors is a security risk. Exception handler lambdaAn alternative to a is to provide a lambda to UseExceptionHandler. Using a lambda allows access to the error before returning the response. The following code uses a lambda for exception handling:
Warning Do not serve sensitive error information to clients. Serving errors is a security risk. IExceptionHandleris an interface that gives the developer a callback for handling known exceptions in a central location.
06 implementations are registered by calling . The lifetime of an
06 instance is singleton. Multiple implementations can be added, and they're called in the order registered. If an exception handler handles a request, it can return
09 to stop processing. If an exception isn't handled by any exception handler, then control falls back to the default behavior and options from the middleware. Different metrics and logs are emitted for handled versus unhandled exceptions. The following example shows an
06 implementation:
The following example shows how to register an
06 implementation for dependency injection:
When the preceding code runs in the Development environment:
In other environments:
UseStatusCodePagesBy default, an ASP.NET Core app doesn't provide a status code page for HTTP error status codes, such as 404 - Not Found. When the app sets an HTTP 400-599 error status code that doesn't have a body, it returns the status code and an empty response body. To enable default text-only handlers for common error status codes, call UseStatusCodePages in
19:
Call
20 before request handling middleware. For example, call
20 before the Static File Middleware and the Endpoints Middleware. When
20 isn't used, navigating to a URL without an endpoint returns a browser-dependent error message indicating the endpoint can't be found. When
20 is called, the browser returns the following response:
20 isn't typically used in production because it returns a message that isn't useful to users. Note The status code pages middleware does not catch exceptions. To provide a custom error handling page, use the . UseStatusCodePages with format stringTo customize the response content type and text, use the overload of UseStatusCodePages that takes a content type and format string:
In the preceding code,
25 is a placeholder for the error code.
20 with a format string isn't typically used in production because it returns a message that isn't useful to users. UseStatusCodePages with lambdaTo specify custom error-handling and response-writing code, use the overload of UseStatusCodePages that takes a lambda expression:
20 with a lambda isn't typically used in production because it returns a message that isn't useful to users. UseStatusCodePagesWithRedirectsThe UseStatusCodePagesWithRedirects extension method:
The URL template can include a
25 placeholder for the status code, as shown in the preceding code. If the URL template starts with
29 (tilde), the
29 is replaced by the app's
31. When specifying an endpoint in the app, create an MVC view or Razor page for the endpoint. This method is commonly used when the app:
UseStatusCodePagesWithReExecuteThe UseStatusCodePagesWithReExecute extension method:
The new pipeline execution may alter the response's status code, as the new pipeline has full control of the status code. If the new pipeline does not alter the status code, the original status code will be sent to the client.
0 If an endpoint within the app is specified, create an MVC view or Razor page for the endpoint. This method is commonly used when the app should:
The URL template must start with
32 and may include a placeholder
25 for the status code. To pass the status code as a query-string parameter, pass a second argument into
34. For example:
1 The endpoint that processes the error can get the original URL that generated the error, as shown in the following example:
2 Since this middleware can re-execute the request pipeline:
Disable status code pagesTo disable status code pages for an MVC controller or action method, use the [SkipStatusCodePages] attribute. To disable status code pages for specific requests in a Razor Pages handler method or in an MVC controller, use IStatusCodePagesFeature:
3 Exception-handling codeCode in exception handling pages can also throw exceptions. Production error pages should be tested thoroughly and take extra care to avoid throwing exceptions of their own. Response headersOnce the headers for a response are sent:
Server exception handlingIn addition to the exception handling logic in an app, the HTTP server implementation can handle some exceptions. If the server catches an exception before response headers are sent, the server sends a
37 response without a response body. If the server catches an exception after response headers are sent, the server closes the connection. Requests that aren't handled by the app are handled by the server. Any exception that occurs when the server is handling the request is handled by the server's exception handling. The app's custom error pages, exception handling middleware, and filters don't affect this behavior. Startup exception handlingOnly the hosting layer can handle exceptions that take place during app startup. The host can be configured to and . The hosting layer can show an error page for a captured startup error only if the error occurs after host address/port binding. If binding fails:
When running on IIS (or Azure App Service) or IIS Express, a 502.5 - Process Failure is returned by the ASP.NET Core Module if the process can't start. For more information, see Troubleshoot ASP.NET Core on Azure App Service and IIS. Database error pageThe Database developer page exception filter AddDatabaseDeveloperPageExceptionFilter captures database-related exceptions that can be resolved by using Entity Framework Core migrations. When these exceptions occur, an HTML response is generated with details of possible actions to resolve the issue. This page is enabled only in the Development environment. The following code adds the Database developer page exception filter:
4 Exception filtersIn MVC apps, exception filters can be configured globally or on a per-controller or per-action basis. In Razor Pages apps, they can be configured globally or per page model. These filters handle any unhandled exceptions that occur during the execution of a controller action or another filter. For more information, see . Exception filters are useful for trapping exceptions that occur within MVC actions, but they're not as flexible as the built-in exception handling middleware, UseExceptionHandler. We recommend using
38, unless you need to perform error handling differently based on which MVC action is chosen. Model state errorsFor information about how to handle model state errors, see Model binding and Model validation. Problem detailsProblem Details are not the only response format to describe an HTTP API error, however, they are commonly used to report errors for HTTP APIs. The problem details service implements the IProblemDetailsService interface, which supports creating problem details in ASP.NET Core. The
39 extension method on IServiceCollection registers the default
40 implementation. In ASP.NET Core apps, the following middleware generates problem details HTTP responses when
39 is called, except when the
42 request HTTP header doesn't include one of the content types supported by the registered IProblemDetailsWriter (default:
43):
The following code configures the app to generate a problem details response for all HTTP client and server error responses that don't have a body content yet:
5 The next section shows how to customize the problem details response body. Customize problem detailsThe automatic creation of a
46 can be customized using any of the following options:
50 operation The generated problem details can be customized using , and the customizations are applied to all auto-generated problem details. The following code uses ProblemDetailsOptions to set :
6 For example, an
51 endpoint result produces the following problem details response body:
7 Custom
48 An IProblemDetailsWriter implementation can be created for advanced customizations.
8 Note: When using a custom
48, the custom
48 must be registered before calling AddRazorPages, AddControllers, AddControllersWithViews, or AddMvc:
9 Problem details from MiddlewareAn alternative approach to using ProblemDetailsOptions with is to set the in middleware. A problem details response can be written by calling
55:
0 In the preceding code, the minimal API endpoints
56 and
57 return the expected custom problem response on error input. The API controller endpoints return the default problem response on error input, not the custom problem response. The default problem response is returned because the API controller has written to the response stream, , before is called and the response is not written again. The following
59 returns BadRequestResult, which writes to the response stream and therefore prevents the custom problem response from being returned.
1 The following
60 returns
61 so the expected custom problem result is returned:
2 Produce a ProblemDetails payload for exceptionsConsider the following app:
3 In non-development environments, when an exception occurs, the following is a standard ProblemDetails response that is returned to the client:
4 For most apps, the preceding code is all that's needed for exceptions. However, the following section shows how to get more detailed problem responses. An alternative to a is to provide a lambda to UseExceptionHandler. Using a lambda allows access to the error and writing a problem details response with
55:
5 Warning Do not serve sensitive error information to clients. Serving errors is a security risk. An alternative approach to generate problem details is to use the third-party NuGet package Hellang.Middleware.ProblemDetails that can be used to map exceptions and client errors to problem details. Additional resources
By Tom Dykstra This article covers common approaches to handling errors in ASP.NET Core web apps. See also Handle errors in ASP.NET Core web APIs and Handle errors in Minimal API apps. Developer exception pageThe Developer Exception Page displays detailed information about unhandled request exceptions. ASP.NET Core apps enable the developer exception page by default when both:
The developer exception page runs early in the middleware pipeline, so that it can catch unhandled exceptions thrown in middleware that follows. Detailed exception information shouldn't be displayed publicly when the app runs in the Production environment. For more information on configuring environments, see Use multiple environments in ASP.NET Core. The Developer Exception Page can include the following information about the exception and the request:
The Developer Exception Page isn't guaranteed to provide any information. Use Logging for complete error information. Exception handler pageTo configure a custom error handling page for the Production environment, call UseExceptionHandler. This exception handling middleware:
Warning If the alternate pipeline throws an exception of its own, Exception Handling Middleware rethrows the original exception. Since this middleware can re-execute the request pipeline:
In the following example, UseExceptionHandler adds the exception handling middleware in non-Development environments:
The Razor Pages app template provides an Error page (
9 action method and an Error view for the Home controller. The exception handling middleware re-executes the request using the original HTTP method. If an error handler endpoint is restricted to a specific set of HTTP methods, it runs only for those HTTP methods. For example, an MVC controller action that uses the
00 attribute runs only for GET requests. To ensure that all requests reach the custom error handling page, don't restrict them to a specific set of HTTP methods. To handle exceptions differently based on the original HTTP method:
To allow unauthenticated users to view the custom error handling page, ensure that it supports anonymous access. Access the exceptionUse IExceptionHandlerPathFeature to access the exception and the original request path in an error handler. The following example uses
05 to get more information about the exception that was thrown:
Warning Do not serve sensitive error information to clients. Serving errors is a security risk. Exception handler lambdaAn alternative to a is to provide a lambda to UseExceptionHandler. Using a lambda allows access to the error before returning the response. The following code uses a lambda for exception handling:
Warning Do not serve sensitive error information to clients. Serving errors is a security risk. UseStatusCodePagesBy default, an ASP.NET Core app doesn't provide a status code page for HTTP error status codes, such as 404 - Not Found. When the app sets an HTTP 400-599 error status code that doesn't have a body, it returns the status code and an empty response body. To enable default text-only handlers for common error status codes, call UseStatusCodePages in
19:
Call
20 before request handling middleware. For example, call
20 before the Static File Middleware and the Endpoints Middleware. When
20 isn't used, navigating to a URL without an endpoint returns a browser-dependent error message indicating the endpoint can't be found. When
20 is called, the browser returns the following response:
20 isn't typically used in production because it returns a message that isn't useful to users. Note The status code pages middleware does not catch exceptions. To provide a custom error handling page, use the . UseStatusCodePages with format stringTo customize the response content type and text, use the overload of UseStatusCodePages that takes a content type and format string:
In the preceding code,
25 is a placeholder for the error code.
20 with a format string isn't typically used in production because it returns a message that isn't useful to users. UseStatusCodePages with lambdaTo specify custom error-handling and response-writing code, use the overload of UseStatusCodePages that takes a lambda expression:
20 with a lambda isn't typically used in production because it returns a message that isn't useful to users. UseStatusCodePagesWithRedirectsThe UseStatusCodePagesWithRedirects extension method:
The URL template can include a
25 placeholder for the status code, as shown in the preceding code. If the URL template starts with
29 (tilde), the
29 is replaced by the app's
31. When specifying an endpoint in the app, create an MVC view or Razor page for the endpoint. This method is commonly used when the app:
UseStatusCodePagesWithReExecuteThe UseStatusCodePagesWithReExecute extension method:
The new pipeline execution may alter the response's status code, as the new pipeline has full control of the status code. If the new pipeline does not alter the status code, the original status code will be sent to the client.
0 If an endpoint within the app is specified, create an MVC view or Razor page for the endpoint. This method is commonly used when the app should:
The URL template must start with
32 and may include a placeholder
25 for the status code. To pass the status code as a query-string parameter, pass a second argument into
34. For example:
1 The endpoint that processes the error can get the original URL that generated the error, as shown in the following example:
2 Since this middleware can re-execute the request pipeline:
Disable status code pagesTo disable status code pages for an MVC controller or action method, use the [SkipStatusCodePages] attribute. To disable status code pages for specific requests in a Razor Pages handler method or in an MVC controller, use IStatusCodePagesFeature:
3 Exception-handling codeCode in exception handling pages can also throw exceptions. Production error pages should be tested thoroughly and take extra care to avoid throwing exceptions of their own. Response headersOnce the headers for a response are sent:
Server exception handlingIn addition to the exception handling logic in an app, the HTTP server implementation can handle some exceptions. If the server catches an exception before response headers are sent, the server sends a
37 response without a response body. If the server catches an exception after response headers are sent, the server closes the connection. Requests that aren't handled by the app are handled by the server. Any exception that occurs when the server is handling the request is handled by the server's exception handling. The app's custom error pages, exception handling middleware, and filters don't affect this behavior. Startup exception handlingOnly the hosting layer can handle exceptions that take place during app startup. The host can be configured to and . The hosting layer can show an error page for a captured startup error only if the error occurs after host address/port binding. If binding fails:
When running on IIS (or Azure App Service) or IIS Express, a 502.5 - Process Failure is returned by the ASP.NET Core Module if the process can't start. For more information, see Troubleshoot ASP.NET Core on Azure App Service and IIS. Database error pageThe Database developer page exception filter AddDatabaseDeveloperPageExceptionFilter captures database-related exceptions that can be resolved by using Entity Framework Core migrations. When these exceptions occur, an HTML response is generated with details of possible actions to resolve the issue. This page is enabled only in the Development environment. The following code adds the Database developer page exception filter:
4 Exception filtersIn MVC apps, exception filters can be configured globally or on a per-controller or per-action basis. In Razor Pages apps, they can be configured globally or per page model. These filters handle any unhandled exceptions that occur during the execution of a controller action or another filter. For more information, see . Exception filters are useful for trapping exceptions that occur within MVC actions, but they're not as flexible as the built-in exception handling middleware, UseExceptionHandler. We recommend using
38, unless you need to perform error handling differently based on which MVC action is chosen. Model state errorsFor information about how to handle model state errors, see Model binding and Model validation. Problem detailsProblem Details are not the only response format to describe an HTTP API error, however, they are commonly used to report errors for HTTP APIs. The problem details service implements the IProblemDetailsService interface, which supports creating problem details in ASP.NET Core. The
39 extension method on IServiceCollection registers the default
40 implementation. In ASP.NET Core apps, the following middleware generates problem details HTTP responses when
39 is called, except when the
42 request HTTP header doesn't include one of the content types supported by the registered IProblemDetailsWriter (default:
43):
The following code configures the app to generate a problem details response for all HTTP client and server error responses that don't have a body content yet:
5 The next section shows how to customize the problem details response body. Customize problem detailsThe automatic creation of a
46 can be customized using any of the following options:
50 operation The generated problem details can be customized using , and the customizations are applied to all auto-generated problem details. The following code uses ProblemDetailsOptions to set :
6 For example, an
51 endpoint result produces the following problem details response body:
7 Custom
48 An IProblemDetailsWriter implementation can be created for advanced customizations.
8 Note: When using a custom
48, the custom
48 must be registered before calling AddRazorPages, AddControllers, AddControllersWithViews, or AddMvc:
9 Problem details from MiddlewareAn alternative approach to using ProblemDetailsOptions with is to set the in middleware. A problem details response can be written by calling
55:
0 In the preceding code, the minimal API endpoints
56 and
57 return the expected custom problem response on error input. The API controller endpoints return the default problem response on error input, not the custom problem response. The default problem response is returned because the API controller has written to the response stream, , before is called and the response is not written again. The following
59 returns BadRequestResult, which writes to the response stream and therefore prevents the custom problem response from being returned.
1 The following
60 returns
61 so the expected custom problem result is returned:
2 Produce a ProblemDetails payload for exceptionsConsider the following app:
3 In non-development environments, when an exception occurs, the following is a standard ProblemDetails response that is returned to the client:
4 For most apps, the preceding code is all that's needed for exceptions. However, the following section shows how to get more detailed problem responses. An alternative to a is to provide a lambda to UseExceptionHandler. Using a lambda allows access to the error and writing a problem details response with
55:
5 Warning Do not serve sensitive error information to clients. Serving errors is a security risk. An alternative approach to generate problem details is to use the third-party NuGet package Hellang.Middleware.ProblemDetails that can be used to map exceptions and client errors to problem details. Additional resources
By Tom Dykstra This article covers common approaches to handling errors in ASP.NET Core web apps. See Handle errors in ASP.NET Core web APIs for web APIs. Developer exception pageThe Developer Exception Page displays detailed information about unhandled request exceptions. ASP.NET Core apps enable the developer exception page by default when both:
The developer exception page runs early in the middleware pipeline, so that it can catch unhandled exceptions thrown in middleware that follows. Detailed exception information shouldn't be displayed publicly when the app runs in the Production environment. For more information on configuring environments, see Use multiple environments in ASP.NET Core. The Developer Exception Page can include the following information about the exception and the request:
The Developer Exception Page isn't guaranteed to provide any information. Use Logging for complete error information. Exception handler pageTo configure a custom error handling page for the Production environment, call UseExceptionHandler. This exception handling middleware:
Warning If the alternate pipeline throws an exception of its own, Exception Handling Middleware rethrows the original exception. In the following example, UseExceptionHandler adds the exception handling middleware in non-Development environments:
The Razor Pages app template provides an Error page (
9 action method and an Error view for the Home controller. The exception handling middleware re-executes the request using the original HTTP method. If an error handler endpoint is restricted to a specific set of HTTP methods, it runs only for those HTTP methods. For example, an MVC controller action that uses the
00 attribute runs only for GET requests. To ensure that all requests reach the custom error handling page, don't restrict them to a specific set of HTTP methods. To handle exceptions differently based on the original HTTP method:
To allow unauthenticated users to view the custom error handling page, ensure that it supports anonymous access. Access the exceptionUse IExceptionHandlerPathFeature to access the exception and the original request path in an error handler. The following example uses
05 to get more information about the exception that was thrown:
Warning Do not serve sensitive error information to clients. Serving errors is a security risk. Exception handler lambdaAn alternative to a is to provide a lambda to UseExceptionHandler. Using a lambda allows access to the error before returning the response. The following code uses a lambda for exception handling:
Warning Do not serve sensitive error information to clients. Serving errors is a security risk. UseStatusCodePagesBy default, an ASP.NET Core app doesn't provide a status code page for HTTP error status codes, such as 404 - Not Found. When the app sets an HTTP 400-599 error status code that doesn't have a body, it returns the status code and an empty response body. To enable default text-only handlers for common error status codes, call UseStatusCodePages in
19:
Call
20 before request handling middleware. For example, call
20 before the Static File Middleware and the Endpoints Middleware. When
20 isn't used, navigating to a URL without an endpoint returns a browser-dependent error message indicating the endpoint can't be found. When
20 is called, the browser returns the following response:
20 isn't typically used in production because it returns a message that isn't useful to users. Note The status code pages middleware does not catch exceptions. To provide a custom error handling page, use the . UseStatusCodePages with format stringTo customize the response content type and text, use the overload of UseStatusCodePages that takes a content type and format string:
In the preceding code,
25 is a placeholder for the error code.
20 with a format string isn't typically used in production because it returns a message that isn't useful to users. UseStatusCodePages with lambdaTo specify custom error-handling and response-writing code, use the overload of UseStatusCodePages that takes a lambda expression:
20 with a lambda isn't typically used in production because it returns a message that isn't useful to users. UseStatusCodePagesWithRedirectsThe UseStatusCodePagesWithRedirects extension method:
The URL template can include a
25 placeholder for the status code, as shown in the preceding code. If the URL template starts with
29 (tilde), the
29 is replaced by the app's
31. When specifying an endpoint in the app, create an MVC view or Razor page for the endpoint. This method is commonly used when the app:
UseStatusCodePagesWithReExecuteThe UseStatusCodePagesWithReExecute extension method:
0 If an endpoint within the app is specified, create an MVC view or Razor page for the endpoint. This method is commonly used when the app should:
The URL template must start with
32 and may include a placeholder
25 for the status code. To pass the status code as a query-string parameter, pass a second argument into
34. For example:
9 The endpoint that processes the error can get the original URL that generated the error, as shown in the following example:
2 Disable status code pagesTo disable status code pages for an MVC controller or action method, use the [SkipStatusCodePages] attribute. To disable status code pages for specific requests in a Razor Pages handler method or in an MVC controller, use IStatusCodePagesFeature:
3 Exception-handling codeCode in exception handling pages can also throw exceptions. Production error pages should be tested thoroughly and take extra care to avoid throwing exceptions of their own. Response headersOnce the headers for a response are sent:
Server exception handlingIn addition to the exception handling logic in an app, the HTTP server implementation can handle some exceptions. If the server catches an exception before response headers are sent, the server sends a
37 response without a response body. If the server catches an exception after response headers are sent, the server closes the connection. Requests that aren't handled by the app are handled by the server. Any exception that occurs when the server is handling the request is handled by the server's exception handling. The app's custom error pages, exception handling middleware, and filters don't affect this behavior. Startup exception handlingOnly the hosting layer can handle exceptions that take place during app startup. The host can be configured to and . The hosting layer can show an error page for a captured startup error only if the error occurs after host address/port binding. If binding fails:
When running on IIS (or Azure App Service) or IIS Express, a 502.5 - Process Failure is returned by the ASP.NET Core Module if the process can't start. For more information, see Troubleshoot ASP.NET Core on Azure App Service and IIS. Database error pageThe Database developer page exception filter AddDatabaseDeveloperPageExceptionFilter captures database-related exceptions that can be resolved by using Entity Framework Core migrations. When these exceptions occur, an HTML response is generated with details of possible actions to resolve the issue. This page is enabled only in the Development environment. The following code adds the Database developer page exception filter:
4 Exception filtersIn MVC apps, exception filters can be configured globally or on a per-controller or per-action basis. In Razor Pages apps, they can be configured globally or per page model. These filters handle any unhandled exceptions that occur during the execution of a controller action or another filter. For more information, see . Exception filters are useful for trapping exceptions that occur within MVC actions, but they're not as flexible as the built-in exception handling middleware, UseExceptionHandler. We recommend using
38, unless you need to perform error handling differently based on which MVC action is chosen. Model state errorsFor information about how to handle model state errors, see Model binding and Model validation. Additional resources
By Kirk Larkin, Tom Dykstra, and Steve Smith This article covers common approaches to handling errors in ASP.NET Core web apps. See Handle errors in ASP.NET Core web APIs for web APIs. View or download sample code. (.) The network tab on the F12 browser developer tools is useful when testing the sample app. Developer Exception PageThe Developer Exception Page displays detailed information about unhandled request exceptions. The ASP.NET Core templates generate the following code:
3 The preceding highlighted code enables the developer exception page when the app is running in the Development environment. The templates place UseDeveloperExceptionPage early in the middleware pipeline so that it can catch unhandled exceptions thrown in middleware that follows. The preceding code enables the Developer Exception Page only when the app runs in the Development environment. Detailed exception information shouldn't be displayed publicly when the app runs in the Production environment. For more information on configuring environments, see Use multiple environments in ASP.NET Core. The Developer Exception Page can include the following information about the exception and the request:
The Developer Exception Page isn't guaranteed to provide any information. Use Logging for complete error information. Exception handler pageTo configure a custom error handling page for the Production environment, call UseExceptionHandler. This exception handling middleware:
Warning If the alternate pipeline throws an exception of its own, Exception Handling Middleware rethrows the original exception. In the following example, UseExceptionHandler adds the exception handling middleware in non-Development environments:
4 The Razor Pages app template provides an Error page (
9 action method and an Error view for the Home controller. The exception handling middleware re-executes the request using the original HTTP method. If an error handler endpoint is restricted to a specific set of HTTP methods, it runs only for those HTTP methods. For example, an MVC controller action that uses the
00 attribute runs only for GET requests. To ensure that all requests reach the custom error handling page, don't restrict them to a specific set of HTTP methods. To handle exceptions differently based on the original HTTP method:
To allow unauthenticated users to view the custom error handling page, ensure that it supports anonymous access. Access the exceptionUse IExceptionHandlerPathFeature to access the exception and the original request path in an error handler. The following code adds
62 to the default
63 generated by the ASP.NET Core templates:
5 Warning Do not serve sensitive error information to clients. Serving errors is a security risk. To test the exception in the sample app:
Exception handler lambdaAn alternative to a is to provide a lambda to UseExceptionHandler. Using a lambda allows access to the error before returning the response. The following code uses a lambda for exception handling:
6 To test the exception handling lambda in the sample app:
UseStatusCodePagesBy default, an ASP.NET Core app doesn't provide a status code page for HTTP error status codes, such as 404 - Not Found. When the app sets an HTTP 400-599 error status code that doesn't have a body, it returns the status code and an empty response body. To provide status code pages, use the status code pages middleware. To enable default text-only handlers for common error status codes, call UseStatusCodePages in the
68 method:
7 Call
20 before request handling middleware. For example, call
20 before the Static File Middleware and the Endpoints Middleware. When
20 isn't used, navigating to a URL without an endpoint returns a browser-dependent error message indicating the endpoint can't be found. For example, navigating to
72. When
20 is called, the browser returns:
20 isn't typically used in production because it returns a message that isn't useful to users. To test
20 in the sample app:
Note The status code pages middleware does not catch exceptions. To provide a custom error handling page, use the . UseStatusCodePages with format stringTo customize the response content type and text, use the overload of UseStatusCodePages that takes a content type and format string:
9 In the preceding code,
25 is a placeholder for the error code.
20 with a format string isn't typically used in production because it returns a message that isn't useful to users. To test
20 in the sample app, remove the comments from
81 in
19. UseStatusCodePages with lambdaTo specify custom error-handling and response-writing code, use the overload of UseStatusCodePages that takes a lambda expression:
0
20 with a lambda isn't typically used in production because it returns a message that isn't useful to users. To test
20 in the sample app, remove the comments from
85 in
19. UseStatusCodePagesWithRedirectsThe UseStatusCodePagesWithRedirects extension method:
1 The URL template can include a
25 placeholder for the status code, as shown in the preceding code. If the URL template starts with
29 (tilde), the
29 is replaced by the app's
31. When specifying an endpoint in the app, create an MVC view or Razor page for the endpoint. For a Razor Pages example, see Pages/MyStatusCode.cshtml in the sample app. This method is commonly used when the app:
To test
20 in the sample app, remove the comments from
92 in
19. UseStatusCodePagesWithReExecuteThe UseStatusCodePagesWithReExecute extension method:
2 If an endpoint within the app is specified, create an MVC view or Razor page for the endpoint. Ensure
34 is placed before
95 so the request can be rerouted to the status page. For a Razor Pages example, see Pages/MyStatusCode2.cshtml in the sample app. This method is commonly used when the app should:
The URL and query string templates may include a placeholder
25 for the status code. The URL template must start with
32. The endpoint that processes the error can get the original URL that generated the error, as shown in the following example:
3 For a Razor Pages example, see Pages/MyStatusCode2.cshtml in the sample app. To test
20 in the sample app, remove the comments from
99 in
19. Disable status code pagesTo disable status code pages for an MVC controller or action method, use the [SkipStatusCodePages] attribute. To disable status code pages for specific requests in a Razor Pages handler method or in an MVC controller, use IStatusCodePagesFeature:
4 Exception-handling codeCode in exception handling pages can also throw exceptions. Production error pages should be tested thoroughly and take extra care to avoid throwing exceptions of their own. Response headersOnce the headers for a response are sent:
Server exception handlingIn addition to the exception handling logic in an app, the HTTP server implementation can handle some exceptions. If the server catches an exception before response headers are sent, the server sends a
37 response without a response body. If the server catches an exception after response headers are sent, the server closes the connection. Requests that aren't handled by the app are handled by the server. Any exception that occurs when the server is handling the request is handled by the server's exception handling. The app's custom error pages, exception handling middleware, and filters don't affect this behavior. Startup exception handlingOnly the hosting layer can handle exceptions that take place during app startup. The host can be configured to and . The hosting layer can show an error page for a captured startup error only if the error occurs after host address/port binding. If binding fails:
When running on IIS (or Azure App Service) or IIS Express, a 502.5 - Process Failure is returned by the ASP.NET Core Module if the process can't start. For more information, see Troubleshoot ASP.NET Core on Azure App Service and IIS. Database error pageThe Database developer page exception filter
02 captures database-related exceptions that can be resolved by using Entity Framework Core migrations. When these exceptions occur, an HTML response is generated with details of possible actions to resolve the issue. This page is enabled only in the Development environment. The following code was generated by the ASP.NET Core Razor Pages templates when individual user accounts were specified:
5 Exception filtersIn MVC apps, exception filters can be configured globally or on a per-controller or per-action basis. In Razor Pages apps, they can be configured globally or per page model. These filters handle any unhandled exceptions that occur during the execution of a controller action or another filter. For more information, see . Exception filters are useful for trapping exceptions that occur within MVC actions, but they're not as flexible as the built-in exception handling middleware,
38. We recommend using
38, unless you need to perform error handling differently based on which MVC action is chosen.
3 Model state errorsFor information about how to handle model state errors, see Model binding and Model validation. Additional resources
By Tom Dykstra, and Steve Smith This article covers common approaches to handling errors in ASP.NET Core web apps. See Handle errors in ASP.NET Core web APIs for web APIs. View or download sample code. (.) Developer Exception PageThe Developer Exception Page displays detailed information about request exceptions. The ASP.NET Core templates generate the following code:
4 The preceding code enables the developer exception page when the app is running in the Development environment. The templates place UseDeveloperExceptionPage before any middleware so exceptions are caught in the middleware that follows. The preceding code enables the Developer Exception Page only when the app is running in the Development environment. Detailed exception information should not be displayed publicly when the app runs in production. For more information on configuring environments, see Use multiple environments in ASP.NET Core. The Developer Exception Page includes the following information about the exception and the request:
Exception handler pageTo configure a custom error handling page for the Production environment, use the Exception Handling Middleware. The middleware:
In the following example, UseExceptionHandler adds the Exception Handling Middleware in non-Development environments:
4 The Razor Pages app template provides an Error page (
Don't mark the error handler action method with HTTP method attributes, such as
08. Explicit verbs prevent some requests from reaching the method. Allow anonymous access to the method if unauthenticated users should see the error view. Access the exceptionUse IExceptionHandlerPathFeature to access the exception and the original request path in an error handler controller or page:
9 Warning Do not serve sensitive error information to clients. Serving errors is a security risk. To trigger the preceding exception handling page, set the environment to productions and force an exception. Exception handler lambdaAn alternative to a is to provide a lambda to UseExceptionHandler. Using a lambda allows access to the error before returning the response. Here's an example of using a lambda for exception handling:
0 In the preceding code,
09 is added so the Internet Explorer browser displays the error message rather than an IE error message. For more information, see this GitHub issue. To see the result of the exception handling lambda in the sample app, use the
10 and
11 preprocessor directives, and select Trigger an exception on the home page. UseStatusCodePagesBy default, an ASP.NET Core app doesn't provide a status code page for HTTP status codes, such as 404 - Not Found. The app returns a status code and an empty response body. To provide status code pages, use Status Code Pages middleware. The middleware is made available by the Microsoft.AspNetCore.Diagnostics package. To enable default text-only handlers for common error status codes, call UseStatusCodePages in the
68 method:
1 Call
20 before request handling middleware (for example, Static File Middleware and MVC Middleware). When
20 isn't used, navigating to a URL without an endpoint returns a browser dependent error message indicating the endpoint can't be found. For example, navigating to
72. When
20 is called, the browser returns:
UseStatusCodePages with format stringTo customize the response content type and text, use the overload of UseStatusCodePages that takes a content type and format string:
3 UseStatusCodePages with lambdaTo specify custom error-handling and response-writing code, use the overload of UseStatusCodePages that takes a lambda expression:
4 UseStatusCodePagesWithRedirectsThe UseStatusCodePagesWithRedirects extension method:
5 The URL template can include a
25 placeholder for the status code, as shown in the example. If the URL template starts with
29 (tilde), the
29 is replaced by the app's
31. If you point to an endpoint within the app, create an MVC view or Razor page for the endpoint. For a Razor Pages example, see
21 in the sample app. This method is commonly used when the app:
UseStatusCodePagesWithReExecuteThe UseStatusCodePagesWithReExecute extension method:
6 If you point to an endpoint within the app, create an MVC view or Razor page for the endpoint. Ensure
34 is placed before
95 so the request can be rerouted to the status page. For a Razor Pages example, see
21 in the sample app. This method is commonly used when the app should:
The URL and query string templates may include a placeholder (
32). When using a placeholder in the path, confirm that the endpoint (page or controller) can process the path segment. For example, a Razor Page for errors should accept the optional path segment value with the
27 directive:
7 The endpoint that processes the error can get the original URL that generated the error, as shown in the following example:
8 Don't mark the error handler action method with HTTP method attributes, such as
08. Explicit verbs prevent some requests from reaching the method. Allow anonymous access to the method if unauthenticated users should see the error view. Disable status code pagesTo disable status code pages for an MVC controller or action method, use the
29 attribute. To disable status code pages for specific requests in a Razor Pages handler method or in an MVC controller, use IStatusCodePagesFeature:
9 Exception-handling codeCode in exception handling pages can throw exceptions. It's often a good idea for production error pages to consist of purely static content. Response headersOnce the headers for a response are sent:
Server exception handlingIn addition to the exception handling logic in your app, the HTTP server implementation can handle some exceptions. If the server catches an exception before response headers are sent, the server sends a 500 - Internal Server Error response without a response body. If the server catches an exception after response headers are sent, the server closes the connection. Requests that aren't handled by your app are handled by the server. Any exception that occurs when the server is handling the request is handled by the server's exception handling. The app's custom error pages, exception handling middleware, and filters don't affect this behavior. Startup exception handlingOnly the hosting layer can handle exceptions that take place during app startup. The host can be configured to and . The hosting layer can show an error page for a captured startup error only if the error occurs after host address/port binding. If binding fails:
When running on IIS (or Azure App Service) or IIS Express, a 502.5 - Process Failure is returned by the ASP.NET Core Module if the process can't start. For more information, see Troubleshoot ASP.NET Core on Azure App Service and IIS. Database error pageDatabase Error Page Middleware captures database-related exceptions that can be resolved by using Entity Framework migrations. When these exceptions occur, an HTML response with details of possible actions to resolve the issue is generated. This page should be enabled only in the Development environment. Enable the page by adding code to
68:
0 UseDatabaseErrorPage requires the Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore NuGet package. Exception filtersIn MVC apps, exception filters can be configured globally or on a per-controller or per-action basis. In Razor Pages apps, they can be configured globally or per page model. These filters handle any unhandled exception that occurs during the execution of a controller action or another filter. For more information, see . Tip Exception filters are useful for trapping exceptions that occur within MVC actions, but they're not as flexible as the Exception Handling Middleware. We recommend using the middleware. Use filters only where you need to perform error handling differently based on which MVC action is chosen. Model state errorsFor information about how to handle model state errors, see Model binding and Model validation. Additional resources
Collaborate with us on GitHub The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide. |