I am working in ASP.NET MVC. I am using partial views, but when I clicked on particular link I got the following error.
500 Internal Server Error
How can this error be fixed?
asked Jun 8, 2010 at 9:32
2
To check what causes Internal Server 500 Error under ASP MVC you can also run your app in debug mode and check property AllErrors.
The property is an array of Exception type elements.
To do this open Global.asax.cs
(C#) and in the body of class MvcApplication
put method Application_EndRequest
:
protected void Application_EndRequest()
{ //here breakpoint
// under debug mode you can find the exceptions at code: this.Context.AllErrors
}
Then set breakpoint and check contents of the array: this.Context.AllErrors
It helped me to resolve what exception was thrown and optionally to see the stacktrace.
Hakan Fıstık
16.5k14 gold badges107 silver badges130 bronze badges
answered Jun 4, 2013 at 11:26
BronekBronek
10.6k2 gold badges45 silver badges46 bronze badges
4
500 Server error means that a script has thrown an error, this is not a broken link (aka a 404 error).
If you are using Internet Explorer, go to tools > options > advanced
and unselect friendly http errors
, this will give you a more comprehensive description of the error so you can debug the script, or contact the relevant people to debug it.
Brian Mains
50.5k35 gold badges145 silver badges256 bronze badges
answered Jun 8, 2010 at 9:46
Tom GullenTom Gullen
60.9k83 gold badges281 silver badges455 bronze badges
I got more details of the error from windows event viewer(Run>eventvwr.msc>Windows Logs>Application). Check the warnings/errors recorded from w3wp.exe
In my case the reason was missing dlls. Hope this helps
answered Jan 12, 2017 at 5:34
sreesree
2,28727 silver badges26 bronze badges
1
Сегодня обсудим, как на asp.net mvc можно настроить обработку ошибок 404, 500, ну и любых других. Рассмотрим на примере 404 и 500, как наиболее популярных и важных. Как вместо стандартного не очень красивого желтого окна ошибки показывать свои собственные красивые интересные страницы, и при этом как правильно отдавать код ошибки в браузер пользователя.
Казалось бы, задача довольно тривиальная и может быть решена написанием буквально пары строк кода. Действительно, так и есть, если вы используете любую популярную серверную технологию. Но только не ASP.NET. Если ваше приложение написано на ASP.NET MVC, и вы первый раз сталкиваетесь с проблемой обработки ошибок, очень легко запутаться и сделать неправильные настройки. Что впоследствии негативно отразится на продвижении сайта в поисковых системах, удобстве работы для пользователя, SEO-оптимизации.
Рассмотрим два подхода, как настроить страницы ошибок. Они в целом похожи, какой выбрать – решать вам.
Для начала вспомним, что означают наиболее популярные коды ошибок, которые отдает сервер.
Код ответа 200. Это значит что все ОК. Запрос клиента обработан успешно, и сервер отдал затребованные клиентом данные в полном объеме. Например, пользователь кликнул по гиперссылке, и в ответ на это в браузере отобразилась нужная ему информация.
Код ответа 404. Это означает, что запрошенный клиентом ресурс не найден на сервере. Например, указанная в адресе гиперссылки статья не найдена, или *.pdf файл был удален и теперь недоступен для скачивания.
Код ответа 500. Внутренняя ошибка на сайте. Что-то сломалось. Это может быть все что угодно, от неправильно написанного кода программистом, до отказа оборудования на сервере.
Допустим, мы только что создали новое веб-приложение типа MVC. На текущий момент, если никаких дополнительных действий для обработки ошибок не принимать, то стандартный сценарий обработки ошибок будет работать как нужно. В браузер пользователя будет отдаваться правильный код ошибки, пользователю будет показана стандартная страница с ошибкой и ее описанием.
Стандартная страница ошибки
Теперь займемся настройкой собственных страниц ошибок. При этом для нас важно не только показать пользователю красивую страницу ошибки, но также сохранить правильный код ответа сервера.
Вариант 1. Ссылка на статичные заранее подготовленные html-страницы.
Первым делом в файле web.config в разделе system.web добавляем новую секцию customErrors со следующими настройками:
web.config
<system.web>
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/404.aspx">
<error statusCode="404" redirect="~/404.aspx"/>
<error statusCode="500" redirect="~/500.aspx"/>
</customErrors>
...
</system.web>
Эта секция служит для обработки ошибок на уровне платформы ASP.NET.
Атрибут mode=»On» определяет, что пользовательские страницы ошибок включены. Также допустимы значения Off / RemoteOnly.
Атрибут redirectMode=»ResponseRewrite» определяет, следует ли изменять URL-адрес запроса при перенаправлении на пользовательскую страницу ошибки. Естественно, нам этого не нужно.
Атрибут defaultRedirect=»~/404.aspx» указывает на то, какая страница ошибки будет показана в случае возникновения кода ответа сервера, который мы не описали в настройках. Пусть при любых других ошибках пользователь будет думать, что страница не найдена.
И уже внутри этой секции мы определяем два кода, для которых у нас будут кастомные страницы ошибок.
Далее, как видно из настроек выше, нам понадобятся *.aspx файлы, на которые будет делаться редирект. Обратите внимание, что мы ссылаемся именно на *.aspx файлы, а не на *.html. Эти файлы являются проходными, служебными, в них содержатся настройки для ответа сервера. Содержимое файла 404.aspx:
404.aspx
<%@ Page Language="C#" %>
<%
var filePath = MapPath("~/404.html");
Response.StatusCode = 404;
Response.ContentType = "text/html; charset=utf-8";
Response.WriteFile(filePath);
%>
В коде выше мы указываем путь непосредственно до конечного *.html файла, а также дополняем настройки ответа сервера. Указываем код ответа, тип отдаваемого контента и кодировку. Если не указать кодировку, то браузер пользователя может интерпретировать ответ от сервера как не отформатированную строку, и, соответственно, не преобразует ее в html-разметку. А если не указать StatusCode = 404 , то получится следующая интересная ситуация:
Код ответа сервера отдается неверно
И хотя на рисунке выше нам показывается пользовательская страница с ошибкой, при этом код ответа 200 — это конечно же неверно. Когда-то давно на форумах Microsoft такое поведение зарепортили как баг. Однако Microsoft возразила, что это не баг, а фича и не стала ничего менять в будущих релизах ASP.NET. Поэтому приходится это исправлять вручную, и вручную в *.aspx файле в ответе сервера указывать код ответа 404.
Попробуйте собственноручно намеренно убрать какую-нибудь из объявленных на данный момент настроек из секции customErrors и понаблюдайте за результатом.
Также по аналогии создаем подобный *.aspx файл для ошибки 500.
И уже после этого нам нужно создать статичные html-файлы, соответственно для ошибок 404 и 500. Пусть они лежат в корне нашего проекта.
Статичные файлы расположены в корне проекта
Здесь же в файле web.config определяем раздел system.WebServer, если он еще не определен, и в нем объявляем секцию httpErrors:
web.config
<system.webServer>
<httpErrors errorMode="Custom" defaultResponseMode="File" defaultPath="c:projectsmysite404.html">
<remove statusCode="404" />
<remove statusCode="500" />
<error statusCode="404" path="404.html" responseMode="File" />
<error statusCode="500" path="500.html" responseMode="File" />
</httpErrors>
</system.webServer>
Эта секция служит для обработки ошибок на уровне сервера IIS. Суть в том, что иногда обработка запроса происходит непосредственно на уровне ASP.NET. А иногда ASP.NET просто определяет нужный код ответа и пропускает запрос выше, на уровень сервера. Такой сценарий может случиться, если, например, мы в действии контроллера возвращаем экземпляр класса HttpNotFound:
Или же когда система маршрутизации в MVC-приложении не может определить, к какому маршруту отнести запрошенный пользователем URL-адрес:
https://site.com/long/long/long/long/path
Для секции httpErrors важно отметить следующее. Так как мы ссылаемся на статичные *.html файлы, то и в качестве значений для нужных атрибутов здесь также указываем File . Для атрибута defaultPath необходимо указать абсолютный путь до файла ошибки. Относительный путь именно в этом месте работать не будет. Сам атрибут defaultPath определяет файл, который будет выбран для всех других ошибок, которые мы явно не указали. Но здесь есть одна небольшая проблема. Дело в том, что этот атрибут по умолчанию заблокирован на сервере IIS Express. Если вы разрабатываете свое приложение именно на локальном сервере, то это ограничение нужно снять. Для этого в директории своего проекта нужно найти файл конфигурации сервера и удалить этот атрибут из заблокированных, как это показано на рисунке:
Расположение файла applicationhost.config
Также проверьте папку App_Start. Если вы создали не пустое приложение, а работаете над реальным проектом, там может находиться класс FilterConfig, в котором регистрируются все глобальные фильтры в приложении. В методе регистрации удалите строчку кода, где регистрируется HandleErrorAttribute, в нашем случае он не понадобится.
Вот такой комплекс мер нужно предпринять, чтобы настроить обработку ошибок 404, 500, и любых других. Это настройки в файле web.config, и добавление в наш проект статичных файлов.
Вариант 2. Обработка ошибок с использованием специального контроллера.
Второй подход немного отличается от первого. Здесь нам не понадобится секция customErrors, так как обработку всех ошибок мы будем передавать сразу из приложения на уровень сервера, и он уже будет решать что делать. Можно удалить или закомментировать эту секцию в файле web.config.
Далее создадим специальный контроллер, который будет принимать все ошибки, которые мы хотим обрабатывать:
public class ErrorController : Controller
{
public ActionResult NotFound()
{
Response.StatusCode = 404;
return View();
}
public ActionResult Internal()
{
Response.StatusCode = 500;
return View();
}
}
Также создадим соответствующие представления с нужной нам красивой разметкой.
Также в файле web.config нам нужно изменить настройки в секции httpErrors. Если раньше мы ссылались на статичные html-файлы, то теперь мы будем обращаться по указанным URL, которые мы определили в ErrorController’е, чтобы именно там обрабатывать ошибки:
web.config
<httpErrors errorMode="Custom" existingResponse="Replace" defaultResponseMode="ExecuteURL" defaultPath="/Error/NotFound">
<remove statusCode="404"/>
<remove statusCode="500"/>
<error statusCode="404" path="/Error/NotFound" responseMode="ExecuteURL"/>
<error statusCode="500" path="/Error/Internal" responseMode="ExecuteURL"/>
</httpErrors>
Вариант 3. Фильтр HandleErrorAttribute
Замечу, что есть еще один способ взять под свой контроль обработку ошибок в приложении – это наследоваться от стандартного класса HandleErrorAttribute и написать свой фильтр. Но это уже более частный случай, когда нужно реализовать какую-то особенную логику при возникновении той или иной ошибки. В большинстве же более менее стандартных приложений наша проблема решается двумя выше описанными способами и в этом фильтре нет необходимости. Более подробную информацию, как работать с классом HandleErrorAttribute можно найти в официальной документации в интернете по этой ссылке.
Итого
Мы посмотрели на два разных подхода, которые можно применить при обработке ошибок на платформе ASP.NET. Опять же повторюсь, что если для вас не принципиально настраивать собственные страницы ошибок, то лучше не изменять эти настройки, так как даже одна упущенная деталь или неверно сконфигурированный параметр может очень сильно навредить репутации вашего сайта для конечного пользователя и в поисковых системах.
- Remove From My Forums
-
Question
-
User1779487221 posted
I am developing an ASP.Net MVC web application and have been publishing it on my own web server as the project develops, allowing my client to review progress. Up until now there have been no problems.
I am now working on my Web API including Entity Framework, data repository and data context and moving from local, in memory, data to accessing the data from a SQL Server database. On my development computer I have created a LocalDb database and my initial
simple code to access this database and retrieve some data builds and runs with no errors.I published this latest version and I get a the following displayed in my browser along with a 500 error:
An error occurred while starting the application.
.NET Core X64 v4.1.1.0 | Microsoft.AspNetCore.Hosting version 1.1.0-rtm-22752 | Microsoft Windows 10.0.14393 | Need
help?When I deployed this version I copied the IndigoDb.mdf and IndigoDb_log.ldf file into the server Administrator’s AppData folder and manually edited the connection string to be as follows:»Data Source=.SQLEXPRESS;AttachDbFileName=|DataDirectory|IndigoDb.mdf;Integrated
Security=SSPI;MultipleActiveResultSets=True»If I comment out the line in my HomeController Index() method, which calls my repository to get some data, and publish the solution everything works fine so it does appear that when the data context tries to connect
to the database it causes the error.I feel sure I have made a simple newbie error here, but I just cannot see it. Any advise would be very welcome.
Answers
-
User753101303 posted
Hi,
And SQL Server Express is installed on the server ? Also if using Integrated Security the account under which the app runs needs to have access to the db (while on a dev machine the code runs under the developer account and so the same account is used to
connect to the db).Anyway it’s best to take the habit to start from an actual error message rather than trying to guess. Try
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling to implement a way to track server side exceptions so that you can start from an actual error message rather than trying to guess what happens…
BTW you have a dedicated
https://forums.asp.net/1255.aspx/1?ASP+NET+Core forum in which you’ll have likely better support.-
Marked as answer by
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by
-
User2053451246 posted
The account under which the app runs — is this the user account which I login to my server with (i.e. Administrator)? If so can you explain how I check that this account has access to the database.
Open IIS, expand your server name, and click Application Pools. Select the pool your application is using and click Advanced Settings… at the right. In the Process Model section you will see the user that IIS is running your app as.
To see which app pool your app is using, select your site’s folder. Then click Advanced Settings… at the right.
-
Marked as answer by
Anonymous
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by
title | author | description | monikerRange | ms.author | ms.custom | ms.date | uid |
---|---|---|---|---|---|---|---|
Handle errors in ASP.NET Core web APIs |
tdykstra |
Learn about error handling with ASP.NET Core web APIs. |
>= aspnetcore-3.1 |
riande |
mvc |
10/14/2022 |
web-api/handle-errors |
Handle errors in ASP.NET Core web APIs
:::moniker range=»>= aspnetcore-7.0″
This article describes how to handle errors and customize error handling with ASP.NET Core web APIs.
Developer Exception Page
The Developer Exception Page shows detailed stack traces for server errors. It uses xref:Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware to capture synchronous and asynchronous exceptions from the HTTP pipeline and to generate error responses. For example, consider the following controller action, which throws an exception:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Controllers/ErrorsController.cs» id=»snippet_Throw»:::
When the Developer Exception Page detects an unhandled exception, it generates a default plain-text response similar to the following example:
HTTP/1.1 500 Internal Server Error Content-Type: text/plain; charset=utf-8 Server: Kestrel Transfer-Encoding: chunked System.Exception: Sample exception. at HandleErrorsSample.Controllers.ErrorsController.Get() in ... at lambda_method1(Closure , Object , Object[] ) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync() at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync() ...
If the client requests an HTML-formatted response, the Developer Exception Page generates a response similar to the following example:
HTTP/1.1 500 Internal Server Error Content-Type: text/html; charset=utf-8 Server: Kestrel Transfer-Encoding: chunked <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Internal Server Error</title> <style> body { font-family: 'Segoe UI', Tahoma, Arial, Helvetica, sans-serif; font-size: .813em; color: #222; background-color: #fff; } h1 { color: #44525e; margin: 15px 0 15px 0; } ...
To request an HTML-formatted response, set the Accept
HTTP request header to text/html
.
[!WARNING]
Don’t enable the Developer Exception Page unless the app is running in the Development environment. Don’t share detailed exception information publicly when the app runs in production. For more information on configuring environments, see xref:fundamentals/environments.
Exception handler
In non-development environments, use Exception Handling Middleware to produce an error payload:
-
In
Program.cs
, call xref:Microsoft.AspNetCore.Builder.ExceptionHandlerExtensions.UseExceptionHandler%2A to add the Exception Handling Middleware::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Program.cs» id=»snippet_Middleware» highlight=»7″:::
-
Configure a controller action to respond to the
/error
route::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Controllers/ErrorsController.cs» id=»snippet_HandleError»:::
The preceding HandleError
action sends an RFC 7807-compliant payload to the client.
[!WARNING]
Don’t mark the error handler action method with HTTP method attributes, such asHttpGet
. Explicit verbs prevent some requests from reaching the action method.For web APIs that use Swagger / OpenAPI, mark the error handler action with the [ApiExplorerSettings] attribute and set its xref:Microsoft.AspNetCore.Mvc.ApiExplorerSettingsAttribute.IgnoreApi%2A property to
true
. This attribute configuration excludes the error handler action from the app’s OpenAPI specification:[ApiExplorerSettings(IgnoreApi = true)]Allow anonymous access to the method if unauthenticated users should see the error.
Exception Handling Middleware can also be used in the Development environment to produce a consistent payload format across all environments:
-
In
Program.cs
, register environment-specific Exception Handling Middleware instances::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ConsistentEnvironments»:::
In the preceding code, the middleware is registered with:
- A route of
/error-development
in the Development environment. - A route of
/error
in non-Development environments.
- A route of
-
Add controller actions for both the Development and non-Development routes:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Controllers/ErrorsController.cs» id=»snippet_ConsistentEnvironments»:::
Use exceptions to modify the response
The contents of the response can be modified from outside of the controller using a custom exception and an action filter:
-
Create a well-known exception type named
HttpResponseException
::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/HttpResponseException.cs» id=»snippet_Class»:::
-
Create an action filter named
HttpResponseExceptionFilter
::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/HttpResponseExceptionFilter.cs» id=»snippet_Class»:::
The preceding filter specifies an
Order
of the maximum integer value minus 10. ThisOrder
allows other filters to run at the end of the pipeline. -
In
Program.cs
, add the action filter to the filters collection::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_AddHttpResponseExceptionFilter»:::
Validation failure error response
For web API controllers, MVC responds with a xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails response type when model validation fails. MVC uses the results of xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.InvalidModelStateResponseFactory to construct the error response for a validation failure. The following example replaces the default factory with an implementation that also supports formatting responses as XML, in Program.cs
:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ConfigureInvalidModelStateResponseFactory»:::
Client error response
An error result is defined as a result with an HTTP status code of 400 or higher. For web API controllers, MVC transforms an error result to produce a xref:Microsoft.AspNetCore.Mvc.ProblemDetails.
The automatic creation of a ProblemDetails
for error status codes is enabled by default, but error responses can be configured in one of the following ways:
- Use the problem details service
- Implement ProblemDetailsFactory
- Use ApiBehaviorOptions.ClientErrorMapping
Default problem details response
The following Program.cs
file was generated by the web application templates for API controllers:
:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Program.cs» id=»snippet_default»:::
Consider the following controller, which returns xref:Microsoft.AspNetCore.Http.HttpResults.BadRequest when the input is invalid:
:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Controllers/ValuesController.cs» id=»snippet_1″:::
A problem details response is generated with the previous code when any of the following conditions apply:
- The
/api/values2/divide
endpoint is called with a zero denominator. - The
/api/values2/squareroot
endpoint is called with a radicand less than zero.
The default problem details response body has the following type
, title
, and status
values:
{ "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1", "title": "Bad Request", "status": 400, "traceId": "00-84c1fd4063c38d9f3900d06e56542d48-85d1d4-00" }
Problem details service
ASP.NET Core supports creating Problem Details for HTTP APIs using the xref:Microsoft.AspNetCore.Http.IProblemDetailsService. For more information, see the Problem details service.
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:
:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Program.cs» id=»snippet_apishort» highlight=»4,8-9,13″:::
Consider the API controller from the previous section, which returns xref:Microsoft.AspNetCore.Http.HttpResults.BadRequest when the input is invalid:
:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Controllers/ValuesController.cs» id=»snippet_1″:::
A problem details response is generated with the previous code when any of the following conditions apply:
- An invalid input is supplied.
- The URI has no matching endpoint.
- An unhandled exception occurs.
The automatic creation of a ProblemDetails
for error status codes is disabled when the xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.SuppressMapClientErrors%2A property is set to true
:
:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Program.cs» id=»snippet_disable» highlight=»4-7″:::
Using the preceding code, when an API controller returns BadRequest
, an HTTP 400 response status is returned with no response body. SuppressMapClientErrors
prevents a ProblemDetails
response from being created, even when calling WriteAsync
for an API Controller endpoint. WriteAsync
is explained later in this article.
The next section shows how to customize the problem details response body, using xref:Microsoft.AspNetCore.Http.ProblemDetailsOptions.CustomizeProblemDetails, to return a more helpful response. For more customization options, see Customizing problem details.
Customize problem details with CustomizeProblemDetails
The following code uses xref:Microsoft.AspNetCore.Http.ProblemDetailsOptions to set xref:Microsoft.AspNetCore.Http.ProblemDetailsOptions.CustomizeProblemDetails:
:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Program.cs» id=»snippet_api_controller» highlight=»6″:::
The updated API controller:
:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Controllers/ValuesController.cs» id=»snippet» highlight=»9-17,27-35″:::
The following code contains the MathErrorFeature
and MathErrorType
, which are used with the preceding sample:
:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/MathErrorFeature.cs» :::
A problem details response is generated with the previous code when any of the following conditions apply:
- The
/divide
endpoint is called with a zero denominator. - The
/squareroot
endpoint is called with a radicand less than zero. - The URI has no matching endpoint.
The problem details response body contains the following when either squareroot
endpoint is called with a radicand less than zero:
{ "type": "https://en.wikipedia.org/wiki/Square_root", "title": "Bad Input", "status": 400, "detail": "Negative or complex numbers are not allowed." }
View or download sample code
Implement ProblemDetailsFactory
MVC uses xref:Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory?displayProperty=fullName to produce all instances of xref:Microsoft.AspNetCore.Mvc.ProblemDetails and xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails. This factory is used for:
- Client error responses
- Validation failure error responses
- xref:Microsoft.AspNetCore.Mvc.ControllerBase.Problem%2A?displayProperty=nameWithType and xref:Microsoft.AspNetCore.Mvc.ControllerBase.ValidationProblem%2A?displayProperty=nameWithType
To customize the problem details response, register a custom implementation of xref:Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory in Program.cs
:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ReplaceProblemDetailsFactory»:::
Use ApiBehaviorOptions.ClientErrorMapping
Use the xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.ClientErrorMapping%2A property to configure the contents of the ProblemDetails
response. For example, the following code in Program.cs
updates the xref:Microsoft.AspNetCore.Mvc.ClientErrorData.Link%2A property for 404 responses:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ClientErrorMapping»:::
Additional resources
- How to Use ModelState Validation in ASP.NET Core Web API
- View or download sample code
- Hellang.Middleware.ProblemDetails
:::moniker-end
:::moniker range=»= aspnetcore-6.0″
This article describes how to handle errors and customize error handling with ASP.NET Core web APIs.
Developer Exception Page
The Developer Exception Page shows detailed stack traces for server errors. It uses xref:Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware to capture synchronous and asynchronous exceptions from the HTTP pipeline and to generate error responses. For example, consider the following controller action, which throws an exception:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Controllers/ErrorsController.cs» id=»snippet_Throw»:::
When the Developer Exception Page detects an unhandled exception, it generates a default plain-text response similar to the following example:
HTTP/1.1 500 Internal Server Error Content-Type: text/plain; charset=utf-8 Server: Kestrel Transfer-Encoding: chunked System.Exception: Sample exception. at HandleErrorsSample.Controllers.ErrorsController.Get() in ... at lambda_method1(Closure , Object , Object[] ) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync() at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync() ...
If the client requests an HTML-formatted response, the Developer Exception Page generates a response similar to the following example:
HTTP/1.1 500 Internal Server Error Content-Type: text/html; charset=utf-8 Server: Kestrel Transfer-Encoding: chunked <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Internal Server Error</title> <style> body { font-family: 'Segoe UI', Tahoma, Arial, Helvetica, sans-serif; font-size: .813em; color: #222; background-color: #fff; } h1 { color: #44525e; margin: 15px 0 15px 0; } ...
To request an HTML-formatted response, set the Accept
HTTP request header to text/html
.
[!WARNING]
Don’t enable the Developer Exception Page unless the app is running in the Development environment. Don’t share detailed exception information publicly when the app runs in production. For more information on configuring environments, see xref:fundamentals/environments.
Exception handler
In non-development environments, use Exception Handling Middleware to produce an error payload:
-
In
Program.cs
, call xref:Microsoft.AspNetCore.Builder.ExceptionHandlerExtensions.UseExceptionHandler%2A to add the Exception Handling Middleware::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Program.cs» id=»snippet_Middleware» highlight=»7″:::
-
Configure a controller action to respond to the
/error
route::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Controllers/ErrorsController.cs» id=»snippet_HandleError»:::
The preceding HandleError
action sends an RFC 7807-compliant payload to the client.
[!WARNING]
Don’t mark the error handler action method with HTTP method attributes, such asHttpGet
. Explicit verbs prevent some requests from reaching the action method.For web APIs that use Swagger / OpenAPI, mark the error handler action with the [ApiExplorerSettings] attribute and set its xref:Microsoft.AspNetCore.Mvc.ApiExplorerSettingsAttribute.IgnoreApi%2A property to
true
. This attribute configuration excludes the error handler action from the app’s OpenAPI specification:[ApiExplorerSettings(IgnoreApi = true)]Allow anonymous access to the method if unauthenticated users should see the error.
Exception Handling Middleware can also be used in the Development environment to produce a consistent payload format across all environments:
-
In
Program.cs
, register environment-specific Exception Handling Middleware instances::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ConsistentEnvironments»:::
In the preceding code, the middleware is registered with:
- A route of
/error-development
in the Development environment. - A route of
/error
in non-Development environments.
- A route of
-
Add controller actions for both the Development and non-Development routes:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Controllers/ErrorsController.cs» id=»snippet_ConsistentEnvironments»:::
Use exceptions to modify the response
The contents of the response can be modified from outside of the controller using a custom exception and an action filter:
-
Create a well-known exception type named
HttpResponseException
::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/HttpResponseException.cs» id=»snippet_Class»:::
-
Create an action filter named
HttpResponseExceptionFilter
::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/HttpResponseExceptionFilter.cs» id=»snippet_Class»:::
The preceding filter specifies an
Order
of the maximum integer value minus 10. ThisOrder
allows other filters to run at the end of the pipeline. -
In
Program.cs
, add the action filter to the filters collection::::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_AddHttpResponseExceptionFilter»:::
Validation failure error response
For web API controllers, MVC responds with a xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails response type when model validation fails. MVC uses the results of xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.InvalidModelStateResponseFactory to construct the error response for a validation failure. The following example replaces the default factory with an implementation that also supports formatting responses as XML, in Program.cs
:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ConfigureInvalidModelStateResponseFactory»:::
Client error response
An error result is defined as a result with an HTTP status code of 400 or higher. For web API controllers, MVC transforms an error result to produce a xref:Microsoft.AspNetCore.Mvc.ProblemDetails.
The error response can be configured in one of the following ways:
- Implement ProblemDetailsFactory
- Use ApiBehaviorOptions.ClientErrorMapping
Implement ProblemDetailsFactory
MVC uses xref:Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory?displayProperty=fullName to produce all instances of xref:Microsoft.AspNetCore.Mvc.ProblemDetails and xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails. This factory is used for:
- Client error responses
- Validation failure error responses
- xref:Microsoft.AspNetCore.Mvc.ControllerBase.Problem%2A?displayProperty=nameWithType and xref:Microsoft.AspNetCore.Mvc.ControllerBase.ValidationProblem%2A?displayProperty=nameWithType
To customize the problem details response, register a custom implementation of xref:Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory in Program.cs
:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ReplaceProblemDetailsFactory»:::
Use ApiBehaviorOptions.ClientErrorMapping
Use the xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.ClientErrorMapping%2A property to configure the contents of the ProblemDetails
response. For example, the following code in Program.cs
updates the xref:Microsoft.AspNetCore.Mvc.ClientErrorData.Link%2A property for 404 responses:
:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ClientErrorMapping»:::
Custom Middleware to handle exceptions
The defaults in the exception handling middleware work well for most apps. For apps that require specialized exception handling, consider customizing the exception handling middleware.
Produce a ProblemDetails payload for exceptions
ASP.NET Core doesn’t produce a standardized error payload when an unhandled exception occurs. For scenarios where it’s desirable to return a standardized ProblemDetails response to the client, the ProblemDetails middleware can be used to map exceptions and 404 responses to a ProblemDetails payload. The exception handling middleware can also be used to return a xref:Microsoft.AspNetCore.Mvc.ProblemDetails payload for unhandled exceptions.
Additional resources
- How to Use ModelState Validation in ASP.NET Core Web API
- View or download sample code (How to download)
:::moniker-end
:::moniker range=»< aspnetcore-6.0″
This article describes how to handle and customize error handling with ASP.NET Core web APIs.
View or download sample code (How to download)
Developer Exception Page
The Developer Exception Page is a useful tool to get detailed stack traces for server errors. It uses xref:Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware to capture synchronous and asynchronous exceptions from the HTTP pipeline and to generate error responses. To illustrate, consider the following controller action:
:::code language=»csharp» source=»handle-errors/samples/3.x/Controllers/WeatherForecastController.cs» id=»snippet_GetByCity»:::
Run the following curl
command to test the preceding action:
curl -i https://localhost:5001/weatherforecast/chicago
The Developer Exception Page displays a plain-text response if the client doesn’t request HTML-formatted output. The following output appears:
HTTP/1.1 500 Internal Server Error Transfer-Encoding: chunked Content-Type: text/plain Server: Microsoft-IIS/10.0 X-Powered-By: ASP.NET Date: Fri, 27 Sep 2019 16:13:16 GMT System.ArgumentException: We don't offer a weather forecast for chicago. (Parameter 'city') at WebApiSample.Controllers.WeatherForecastController.Get(String city) in C:working_folderaspnetAspNetCore.Docsaspnetcoreweb-apihandle-errorssamples3.xControllersWeatherForecastController.cs:line 34 at lambda_method(Closure , Object , Object[] ) at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Logged|12_1(ControllerActionInvoker invoker) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() --- End of stack trace from previous location where exception was thrown --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker) at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) HEADERS ======= Accept: */* Host: localhost:44312 User-Agent: curl/7.55.1
To display an HTML-formatted response instead, set the Accept
HTTP request header to the text/html
media type. For example:
curl -i -H "Accept: text/html" https://localhost:5001/weatherforecast/chicago
Consider the following excerpt from the HTTP response:
HTTP/1.1 500 Internal Server Error Transfer-Encoding: chunked Content-Type: text/html; charset=utf-8 Server: Microsoft-IIS/10.0 X-Powered-By: ASP.NET Date: Fri, 27 Sep 2019 16:55:37 GMT <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Internal Server Error</title> <style> body { font-family: 'Segoe UI', Tahoma, Arial, Helvetica, sans-serif; font-size: .813em; color: #222; background-color: #fff; }
The HTML-formatted response becomes useful when testing via tools like Postman. The following screen capture shows both the plain-text and the HTML-formatted responses in Postman:
:::image source=»handle-errors/_static/developer-exception-page-postman.gif» alt-text=»Test the Developer Exception Page in Postman.»:::
[!WARNING]
Enable the Developer Exception Page only when the app is running in the Development environment. Don’t share detailed exception information publicly when the app runs in production. For more information on configuring environments, see xref:fundamentals/environments.Don’t mark the error handler action method with HTTP method attributes, such as
HttpGet
. Explicit verbs prevent some requests from reaching the action method. Allow anonymous access to the method if unauthenticated users should see the error.
Exception handler
In non-development environments, Exception Handling Middleware can be used to produce an error payload:
-
In
Startup.Configure
, invoke xref:Microsoft.AspNetCore.Builder.ExceptionHandlerExtensions.UseExceptionHandler%2A to use the middleware::::code language=»csharp» source=»handle-errors/samples/3.x/Startup.cs» id=»snippet_UseExceptionHandler» highlight=»9″:::
-
Configure a controller action to respond to the
/error
route::::code language=»csharp» source=»handle-errors/samples/3.x/Controllers/ErrorController.cs» id=»snippet_ErrorController»:::
The preceding Error
action sends an RFC 7807-compliant payload to the client.
Exception Handling Middleware can also provide more detailed content-negotiated output in the local development environment. Use the following steps to produce a consistent payload format across development and production environments:
-
In
Startup.Configure
, register environment-specific Exception Handling Middleware instances:public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseExceptionHandler("/error-local-development"); } else { app.UseExceptionHandler("/error"); } }
In the preceding code, the middleware is registered with:
- A route of
/error-local-development
in the Development environment. - A route of
/error
in environments that aren’t Development.
- A route of
-
Apply attribute routing to controller actions:
:::code language=»csharp» source=»handle-errors/samples/3.x/Controllers/ErrorController.cs» id=»snippet_ErrorControllerEnvironmentSpecific»:::
The preceding code calls ControllerBase.Problem to create a xref:Microsoft.AspNetCore.Mvc.ProblemDetails response.
Use exceptions to modify the response
The contents of the response can be modified from outside of the controller. In ASP.NET 4.x Web API, one way to do this was using the xref:System.Web.Http.HttpResponseException type. ASP.NET Core doesn’t include an equivalent type. Support for HttpResponseException
can be added with the following steps:
-
Create a well-known exception type named
HttpResponseException
::::code language=»csharp» source=»handle-errors/samples/3.x/Exceptions/HttpResponseException.cs» id=»snippet_HttpResponseException»:::
-
Create an action filter named
HttpResponseExceptionFilter
::::code language=»csharp» source=»handle-errors/samples/3.x/Filters/HttpResponseExceptionFilter.cs» id=»snippet_HttpResponseExceptionFilter»:::
The preceding filter specifies an
Order
of the maximum integer value minus 10. ThisOrder
allows other filters to run at the end of the pipeline. -
In
Startup.ConfigureServices
, add the action filter to the filters collection::::code language=»csharp» source=»handle-errors/samples/3.x/Startup.cs» id=»snippet_AddExceptionFilter»:::
Validation failure error response
For web API controllers, MVC responds with a xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails response type when model validation fails. MVC uses the results of xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.InvalidModelStateResponseFactory to construct the error response for a validation failure. The following example uses the factory to change the default response type to xref:Microsoft.AspNetCore.Mvc.SerializableError in Startup.ConfigureServices
:
:::code language=»csharp» source=»handle-errors/samples/3.x/Startup.cs» id=»snippet_DisableProblemDetailsInvalidModelStateResponseFactory» highlight=»4-13″:::
Client error response
An error result is defined as a result with an HTTP status code of 400 or higher. For web API controllers, MVC transforms an error result to a result with xref:Microsoft.AspNetCore.Mvc.ProblemDetails.
The error response can be configured in one of the following ways:
- Implement ProblemDetailsFactory
- Use ApiBehaviorOptions.ClientErrorMapping
Implement ProblemDetailsFactory
MVC uses xref:Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory?displayProperty=fullName to produce all instances of xref:Microsoft.AspNetCore.Mvc.ProblemDetails and xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails. This factory is used for:
- Client error responses
- Validation failure error responses
- xref:Microsoft.AspNetCore.Mvc.ControllerBase.Problem%2A?displayProperty=nameWithType and xref:Microsoft.AspNetCore.Mvc.ControllerBase.ValidationProblem%2A?displayProperty=nameWithType >
To customize the problem details response, register a custom implementation of xref:Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory in Startup.ConfigureServices
:
public void ConfigureServices(IServiceCollection serviceCollection) { services.AddControllers(); services.AddTransient<ProblemDetailsFactory, CustomProblemDetailsFactory>(); }
Use ApiBehaviorOptions.ClientErrorMapping
Use the xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.ClientErrorMapping%2A property to configure the contents of the ProblemDetails
response. For example, the following code in Startup.ConfigureServices
updates the type
property for 404 responses:
:::code language=»csharp» source=»index/samples/3.x/Startup.cs» id=»snippet_ConfigureApiBehaviorOptions» highlight=»8-9″:::
Custom Middleware to handle exceptions
The defaults in the exception handling middleware work well for most apps. For apps that require specialized exception handling, consider customizing the exception handling middleware.
Producing a ProblemDetails payload for exceptions
ASP.NET Core doesn’t produce a standardized error payload when an unhandled exception occurs. For scenarios where it’s desirable to return a standardized ProblemDetails response to the client, the ProblemDetails middleware can be used to map exceptions and 404 responses to a ProblemDetails payload. The exception handling middleware can also be used to return a xref:Microsoft.AspNetCore.Mvc.ProblemDetails payload for unhandled exceptions.
:::moniker-end
I’ve just deployed an update to an existing ASP.NET MVC3 site (it was already configured) and I’m getting the IIS blue screen of death stating
HTTP Error 500.0 — Internal Server Error
The page cannot be displayed because an internal server error has occurred.
However; there is nothing showing up in the Application Event Log where I would expect to see a (more) detailed description of the entry.
How can I go about diagnosing this issue?
asked Jul 15, 2012 at 21:25
Greg BGreg B
1,5885 gold badges17 silver badges32 bronze badges
1
Take a look at IIS7’s Failed Request Tracing feature:
Troubleshooting Failed Requests Using Tracing in IIS 7
Troubleshoot with Failed Request Tracing
The other thing I would do is tweak your <httpErrors>
setting because IIS may be swallowing an error message from further up the pipeline:
<configuration>
<system.webServer>
<httpErrors existingResponse="PassThrough" />
</system.webServer>
</configuration>
If the site is written in Classic ASP then be sure to turn on the Send Errors to Browser setting in the ASP configuration feature:
And finally, if you’re using Internet Explorer then make sure you’ve turned off Show friendly HTTP error messages in the Advanced settings (though I suspect you’ve done that already or are using a different browser).
answered Jul 15, 2012 at 22:10
KevKev
7,84717 gold badges81 silver badges108 bronze badges
2
In my case:
- The Event Log was empty.
web.config
wasn’t corrupt — verified by using same on local machine / usinginetmgr
Finally…
- Checking IIS logs showed a request like this
...Chrome/57.0.2987.133+Safari/537.36 500 19 5 312
The key being:
sc-status sc-substatus sc-win32-status
500 19 5
which with some googling pointed me to the IIS_USRS
not having read permissions to the www
folder
answered May 16, 2017 at 23:25
fiatfiat
78711 silver badges16 bronze badges
1
The most obvious issue is improper or zero NTFS rights on the web application folder. So make sure the account serving the site has the right permissions. Without proper NTFS rights to the web directory it doesn’t matter what you put in the web.config as it will never be read.
A quick check can be to give everyone full rights — if the site starts working then you know it’s a rights problem and you can then set about assigning appropriate rights to a more appropriate account.
answered Sep 10, 2016 at 22:33
rismrism
3012 silver badges12 bronze badges
If upgrading from IIS6, then it may be one of the the web.config works on 6, but not in IIS 7.5 … Double click on all the icons in IIS for the website and you may get an error about the format (Section must be below other section…)
answered May 13, 2013 at 22:11
I had the same problem with an Azure Web App. While debugging locally, error messages (JSON) returned from ajax calls were fully returned to the browser. But once deploy to the Web App, the messages were swallowed and i was returned a default 500 error message.
So I had to explicitly set the existingResponse
value to PassThrough
in the web.config httpErrors
tag.
answered Dec 23, 2015 at 8:45
I ran in this issue many times. 500 error from a ASP.NET 4.x website. No details in the eventLog and even the tracing above didn’t help. In my case it was caused by the fact that the web.config contains rewrite rules. So check your web.config if it has something like:
<system.webServer>
<rewrite>
<rules>
...
</rules>
</rewrite>
</system.webServer>
If it does, you need to install iis rewrite module:
https://www.iis.net/downloads/microsoft/url-rewrite
answered Dec 1, 2021 at 10:47