Asp mvc error 500

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?

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?

Peter Mortensen's user avatar

asked Jun 8, 2010 at 9:32

Renu123's user avatar

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's user avatar

Hakan Fıstık

15.9k12 gold badges103 silver badges127 bronze badges

answered Jun 4, 2013 at 11:26

Bronek's user avatar

BronekBronek

10.5k2 gold badges44 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's user avatar

Brian Mains

50.4k35 gold badges145 silver badges254 bronze badges

answered Jun 8, 2010 at 9:46

Tom Gullen's user avatar

Tom GullenTom Gullen

60.7k82 gold badges280 silver badges453 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

sree's user avatar

sreesree

2,28127 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

Расположение файла 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. Опять же повторюсь, что если для вас не принципиально настраивать собственные страницы ошибок, то лучше не изменять эти настройки, так как даже одна упущенная деталь или неверно сконфигурированный параметр может очень сильно навредить репутации вашего сайта для конечного пользователя и в поисковых системах.

Казалось бы, задача довольно тривиальная и может быть решена написанием буквально пары строк кода. Действительно, так и есть, если вы используете любую популярную серверную технологию. Но только не ASP.NET. Если ваше приложение написано на ASP.NET MVC, и вы первый раз сталкиваетесь с проблемой обработки ошибок, очень легко запутаться и сделать неправильные настройки. Что впоследствии негативно отразится на продвижении сайта в поисковых системах, удобстве работы для пользователя, SEO-оптимизации.

Рассмотрим два подхода, как настроить страницы ошибок. Они в целом похожи, какой выбрать – решать вам.

Для начала вспомним, что означают наиболее популярные коды ошибок, которые отдает сервер.

Допустим, мы только что создали новое веб-приложение типа MVC. На текущий момент, если никаких дополнительных действий для обработки ошибок не принимать, то стандартный сценарий обработки ошибок будет работать как нужно. В браузер пользователя будет отдаваться правильный код ошибки, пользователю будет показана стандартная страница с ошибкой и ее описанием.

Теперь займемся настройкой собственных страниц ошибок. При этом для нас важно не только показать пользователю красивую страницу ошибки, но также сохранить правильный код ответа сервера.

Вариант 1. Ссылка на статичные заранее подготовленные html-страницы.

Первым делом в файле web.config в разделе system.web добавляем новую секцию customErrors со следующими настройками:

Эта секция служит для обработки ошибок на уровне платформы ASP.NET.

Атрибут mode=»On» определяет, что пользовательские страницы ошибок включены. Также допустимы значения Off / RemoteOnly .

Атрибут redirectMode=»ResponseRewrite» определяет, следует ли изменять URL-адрес запроса при перенаправлении на пользовательскую страницу ошибки. Естественно, нам этого не нужно.

/404.aspx» указывает на то, какая страница ошибки будет показана в случае возникновения кода ответа сервера, который мы не описали в настройках. Пусть при любых других ошибках пользователь будет думать, что страница не найдена.

И уже внутри этой секции мы определяем два кода, для которых у нас будут кастомные страницы ошибок.

Далее, как видно из настроек выше, нам понадобятся *.aspx файлы, на которые будет делаться редирект. Обратите внимание, что мы ссылаемся именно на *.aspx файлы, а не на *.html. Эти файлы являются проходными, служебными, в них содержатся настройки для ответа сервера. Содержимое файла 404.aspx:

В коде выше мы указываем путь непосредственно до конечного *.html файла, а также дополняем настройки ответа сервера. Указываем код ответа, тип отдаваемого контента и кодировку. Если не указать кодировку, то браузер пользователя может интерпретировать ответ от сервера как не отформатированную строку, и, соответственно, не преобразует ее в html-разметку. А если не указать StatusCode = 404 , то получится следующая интересная ситуация:

И хотя на рисунке выше нам показывается пользовательская страница с ошибкой, при этом код ответа 200 — это конечно же неверно. Когда-то давно на форумах Microsoft такое поведение зарепортили как баг. Однако Microsoft возразила, что это не баг, а фича и не стала ничего менять в будущих релизах ASP.NET. Поэтому приходится это исправлять вручную, и вручную в *.aspx файле в ответе сервера указывать код ответа 404.

Попробуйте собственноручно намеренно убрать какую-нибудь из объявленных на данный момент настроек из секции customErrors и понаблюдайте за результатом.

Также по аналогии создаем подобный *.aspx файл для ошибки 500.

И уже после этого нам нужно создать статичные html-файлы, соответственно для ошибок 404 и 500. Пусть они лежат в корне нашего проекта.

Здесь же в файле web.config определяем раздел system.WebServer , если он еще не определен, и в нем объявляем секцию httpErrors :

Эта секция служит для обработки ошибок на уровне сервера IIS. Суть в том, что иногда обработка запроса происходит непосредственно на уровне ASP.NET. А иногда ASP.NET просто определяет нужный код ответа и пропускает запрос выше, на уровень сервера. Такой сценарий может случиться, если, например, мы в действии контроллера возвращаем экземпляр класса HttpNotFound :

Или же когда система маршрутизации в MVC-приложении не может определить, к какому маршруту отнести запрошенный пользователем URL-адрес:

Для секции httpErrors важно отметить следующее. Так как мы ссылаемся на статичные *.html файлы, то и в качестве значений для нужных атрибутов здесь также указываем File . Для атрибута defaultPath необходимо указать абсолютный путь до файла ошибки. Относительный путь именно в этом месте работать не будет. Сам атрибут defaultPath определяет файл, который будет выбран для всех других ошибок, которые мы явно не указали. Но здесь есть одна небольшая проблема. Дело в том, что этот атрибут по умолчанию заблокирован на сервере IIS Express. Если вы разрабатываете свое приложение именно на локальном сервере, то это ограничение нужно снять. Для этого в директории своего проекта нужно найти файл конфигурации сервера и удалить этот атрибут из заблокированных, как это показано на рисунке:

Также проверьте папку App_Start . Если вы создали не пустое приложение, а работаете над реальным проектом, там может находиться класс FilterConfig , в котором регистрируются все глобальные фильтры в приложении. В методе регистрации удалите строчку кода, где регистрируется HandleErrorAttribute , в нашем случае он не понадобится.

Вот такой комплекс мер нужно предпринять, чтобы настроить обработку ошибок 404, 500, и любых других. Это настройки в файле web.config, и добавление в наш проект статичных файлов.

Вариант 2. Обработка ошибок с использованием специального контроллера.

Второй подход немного отличается от первого. Здесь нам не понадобится секция customErrors , так как обработку всех ошибок мы будем передавать сразу из приложения на уровень сервера, и он уже будет решать что делать. Можно удалить или закомментировать эту секцию в файле web.config.

Далее создадим специальный контроллер, который будет принимать все ошибки, которые мы хотим обрабатывать:

Также создадим соответствующие представления с нужной нам красивой разметкой.

Также в файле web.config нам нужно изменить настройки в секции httpErrors . Если раньше мы ссылались на статичные html-файлы, то теперь мы будем обращаться по указанным URL, которые мы определили в ErrorController’е , чтобы именно там обрабатывать ошибки:

Вариант 3. Фильтр HandleErrorAttribute

Замечу, что есть еще один способ взять под свой контроль обработку ошибок в приложении – это наследоваться от стандартного класса HandleErrorAttribute и написать свой фильтр. Но это уже более частный случай, когда нужно реализовать какую-то особенную логику при возникновении той или иной ошибки. В большинстве же более менее стандартных приложений наша проблема решается двумя выше описанными способами и в этом фильтре нет необходимости. Более подробную информацию, как работать с классом HandleErrorAttribute можно найти в официальной документации в интернете по этой ссылке.

Источник

Asp mvc error 500

Since you post that you have followed the guidance, could you please confirm that you have completed following steps:

If you confirm that you have prepared all above necessary component for hosting the asp.net core website, the next step is to check if you have access to the web.config file.

  • Ensure that the Identity is set to use ApplicationPoolIdentity.
  • Then check if the publish folder has granted permission to the application pool. (following below steps)

Regarding how to check and grant permission:

  1. Open Windows Explorer
  2. Select the directory for the publish folder where the web.config locates
  3. Right click the directory and select Properties
  4. Select the Security tab
  5. Check if the application pool has been in the list of the group and users.
  6. If not, then add
  7. Click the Edit button and then Add button
  8. Click the Locations button and make sure that you select your computer.
  9. Enter IIS AppPool in the Enter the object names to select: text box.
  10. Click the Check Names button and click OK.
  11. Check Modify under the Allow column, and click OK, and OK.

I could not provide one-shot solution so that we are trying to narrow down the problem and target it.

If you have tried above suggestions with no luck, feel free to let me know.

Источник

Handle errors in ASP.NET Core web APIs

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 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:

When the Developer Exception Page detects an unhandled exception, it generates a default plain-text response similar to the following example:

If the client requests an HTML-formatted response, the Developer Exception Page generates a response similar to the following example:

To request an HTML-formatted response, set the Accept HTTP request header to text/html .

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 Use multiple environments in ASP.NET Core.

Exception handler

In non-development environments, use Exception Handling Middleware to produce an error payload:

In Program.cs , call UseExceptionHandler to add the Exception Handling Middleware:

Configure a controller action to respond to the /error route:

The preceding HandleError action sends an RFC 7807-compliant payload to the client.

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.

For web APIs that use Swagger / OpenAPI, mark the error handler action with the [ApiExplorerSettings] attribute and set its IgnoreApi property to true . This attribute configuration excludes the error handler action from the app’s OpenAPI specification:

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:

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.

Add controller actions for both the Development and non-Development routes:

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 :

Create an action filter named HttpResponseExceptionFilter :

The preceding filter specifies an Order of the maximum integer value minus 10. This Order allows other filters to run at the end of the pipeline.

In Program.cs , add the action filter to the filters collection:

Validation failure error response

For web API controllers, MVC responds with a ValidationProblemDetails response type when model validation fails. MVC uses the results of 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 :

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 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:

Default problem details response

The following Program.cs file was generated by the web application templates for API controllers:

Consider the following controller, which returns BadRequest when the input is invalid:

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:

Problem details service

ASP.NET Core supports creating Problem Details for HTTP APIs using the 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:

Consider the API controller from the previous section, which returns BadRequest when the input is invalid:

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 SuppressMapClientErrors property is set to true :

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 CustomizeProblemDetails, to return a more helpful response. For more customization options, see Customizing problem details.

Customize problem details with CustomizeProblemDetails

The updated API controller:

The following code contains the MathErrorFeature and MathErrorType , which are used with the preceding sample:

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:

Implement ProblemDetailsFactory

To customize the problem details response, register a custom implementation of ProblemDetailsFactory in Program.cs :

Use ApiBehaviorOptions.ClientErrorMapping

Use the ClientErrorMapping property to configure the contents of the ProblemDetails response. For example, the following code in Program.cs updates the Link property for 404 responses:

Additional resources

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 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:

When the Developer Exception Page detects an unhandled exception, it generates a default plain-text response similar to the following example:

If the client requests an HTML-formatted response, the Developer Exception Page generates a response similar to the following example:

To request an HTML-formatted response, set the Accept HTTP request header to text/html .

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 Use multiple environments in ASP.NET Core.

Exception handler

In non-development environments, use Exception Handling Middleware to produce an error payload:

In Program.cs , call UseExceptionHandler to add the Exception Handling Middleware:

Configure a controller action to respond to the /error route:

The preceding HandleError action sends an RFC 7807-compliant payload to the client.

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.

For web APIs that use Swagger / OpenAPI, mark the error handler action with the [ApiExplorerSettings] attribute and set its IgnoreApi property to true . This attribute configuration excludes the error handler action from the app’s OpenAPI specification:

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:

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.

Add controller actions for both the Development and non-Development routes:

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 :

Create an action filter named HttpResponseExceptionFilter :

The preceding filter specifies an Order of the maximum integer value minus 10. This Order allows other filters to run at the end of the pipeline.

In Program.cs , add the action filter to the filters collection:

Validation failure error response

For web API controllers, MVC responds with a ValidationProblemDetails response type when model validation fails. MVC uses the results of 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 :

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 ProblemDetails.

The error response can be configured in one of the following ways:

Implement ProblemDetailsFactory

To customize the problem details response, register a custom implementation of ProblemDetailsFactory in Program.cs :

Use ApiBehaviorOptions.ClientErrorMapping

Use the ClientErrorMapping property to configure the contents of the ProblemDetails response. For example, the following code in Program.cs updates the Link property for 404 responses:

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 ProblemDetails payload for unhandled exceptions.

Additional resources

This article describes how to handle and customize error handling with ASP.NET Core web APIs.

Developer Exception Page

The Developer Exception Page is a useful tool to get detailed stack traces for server errors. It uses DeveloperExceptionPageMiddleware to capture synchronous and asynchronous exceptions from the HTTP pipeline and to generate error responses. To illustrate, consider the following controller action:

Run the following curl command to test the preceding action:

The Developer Exception Page displays a plain-text response if the client doesn’t request HTML-formatted output. The following output appears:

To display an HTML-formatted response instead, set the Accept HTTP request header to the text/html media type. For example:

Consider the following excerpt from the HTTP response:

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:

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 Use multiple environments in ASP.NET Core.

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 UseExceptionHandler to use the middleware:

Configure a controller action to respond to the /error route:

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:

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.

Apply attribute routing to controller actions:

The preceding code calls ControllerBase.Problem to create a 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 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 :

Create an action filter named HttpResponseExceptionFilter :

The preceding filter specifies an Order of the maximum integer value minus 10. This Order allows other filters to run at the end of the pipeline.

In Startup.ConfigureServices , add the action filter to the filters collection:

Validation failure error response

For web API controllers, MVC responds with a ValidationProblemDetails response type when model validation fails. MVC uses the results of InvalidModelStateResponseFactory to construct the error response for a validation failure. The following example uses the factory to change the default response type to SerializableError in Startup.ConfigureServices :

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 ProblemDetails.

The error response can be configured in one of the following ways:

Implement ProblemDetailsFactory

To customize the problem details response, register a custom implementation of ProblemDetailsFactory in Startup.ConfigureServices :

Use ApiBehaviorOptions.ClientErrorMapping

Use the ClientErrorMapping property to configure the contents of the ProblemDetails response. For example, the following code in Startup.ConfigureServices updates the type property for 404 responses:

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.

Источник

  • Remove From My Forums
  • Question

  • User135423268 posted

    Good Day Everyone

    I’m having an error after I deploy my ASP.Net Core MVC website, I follow the instructions on this website

    https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-3.1 and also on this youtube channel
    https://www.youtube.com/watch?v=Q_A_t7KS5Ss but I’m still having the error below.

    HTTP Error 500.19 — Internal Server Error

    The requested page cannot be accessed because the related configuration data for the page is invalid.

    <fieldset>

    Detailed Error Information:

    Module    IIS Web Core
    Notification    Unknown
    Handler    Not yet determined
    Error Code    0x8007000d
    Config Error    
    Config File    \?C:Websiteseappsadminweb.config
    Requested URL    http://localhost:10003/
    Physical Path    
    Logon Method    Not yet determined
    Logon User    Not yet determined

    </fieldset>

    <fieldset>

    Config Source:

       -1: 
        0: 

    I don’t know what to do, I’m losing hope and might try to migrate my system back to .Net Framework.

    </fieldset>

Answers

  • User-1330468790 posted

    Hi amendoza29,

    Since you post that you have followed the guidance, could you please confirm that you have completed following steps: 

    • Enable the Web Server (IIS) server role and establish role services.
    • Install the
      .NET Core Hosting Bundle
    • Install
      Web Deploy when publishing with Visual Studio

    If you confirm that you have prepared all above necessary component for hosting the asp.net core website, the next step is to check if you have access to the web.config file.

    • Ensure that the Identity is set to use ApplicationPoolIdentity. 
    • Then check if the publish folder has granted permission to the
      application pool. (following below steps) 

    Regarding how to check and grant permission:

    1. Open Windows Explorer
    2. Select the directory for the publish folder where the web.config locates
    3. Right click the directory and select Properties
    4. Select the Security tab
    5. Check if the application pool has been in the list of the group and users.
    6. If not, then add
    7. Click the Edit button and then Add button
    8. Click the Locations button and make sure that you select your computer.
    9. Enter IIS AppPool<myappoolname> in the Enter the object names to select: text box.
    10. Click the Check Names button and click OK.
    11. Check Modify under the Allow column, and click OK, and OK.

    I could not provide one-shot solution so that we are trying to narrow down the problem and target it.

    If you have tried above suggestions with no luck, feel free to let me know.

    Best regards,

    Sean

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

I did include the output of dotnet --into output in my original report.

The full stack trace is:

System.InvalidOperationException: The instance of entity type 'TodoItem' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.ThrowIdentityConflict(InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(TKey key, InternalEntityEntry entry, Boolean updateDuplicate)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry entry)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges, Nullable`1 forceStateWhenUnknownKey)
   at Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry.set_State(EntityState value)
   at TodoApi.Controllers.TodoController.PutTodoItem(Int64 id, TodoItem todoItem) in /home/sjm/tmp/Docs/aspnetcore/tutorials/first-web-api/samples/2.2/TodoApi/Controllers/TodoController.cs:line 80
   at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)

The line that causes the exception is:

_context.Entry(todoItem).State = EntityState.Modified;

If I use a different ID in either the URL or payload I get:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "Bad Request",
    "status": 400,
    "traceId": "0HLK5A8VJ9L24:00000001"
}

I’ve found something strange: it only fails if it’s the first request. It seems if I make any other request first (even one that fails), then the PUT works.

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 B's user avatar

Greg BGreg B

1,5585 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:

enter image description here

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

Kev's user avatar

KevKev

7,78717 gold badges79 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 / using inetmgr

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

fiat's user avatar

fiatfiat

77711 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

rism's user avatar

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

M Hall's user avatar

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.

Andrew Urquhart's user avatar

answered Dec 23, 2015 at 8:45

Loul G.'s user avatar

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

Maarten Kieft's user avatar

Понравилась статья? Поделить с друзьями:
  • Asi loader error что делать самп
  • Asi loader error gta sa
  • Asi loader error 126
  • Ashen the game has crashed and will close как исправить
  • Asf cam sensor error как исправить