Asp net core 500 internal server error

:( Oops. 500 Internal Server Error An error occurred while starting the application. This message came out when I added database functionality to my asp.net core app and deployed it to iis. W...

:( Oops.
500 Internal Server Error
An error occurred while starting the application.

This message came out when I added database functionality to my asp.net core app and deployed it to iis. When I developed it in Visual Studio, everything went well. But after deploying, this error messages appeared.

I tried to use dotnet myapp.dll to run my app in the deploy folder, and found out it worked well. It is likely that the problem is relation to iis. I tried to add <compilation debug="true">..</compilation> to web.config, but it seems useless. What is problem are actually, or is there any other way to see the detailed error info to help find out what’s happened?

asked Sep 30, 2016 at 7:14

yitian's user avatar

4

  1. Change stdoutLogEnabled=»false» to true and then check the logs at stdoutLogFile=».logsstdout». The error(s) there might tell you something.

  2. Check that you set up right Environment Name using ASPNETCORE_ENVIRONMENT environment variable as so use correct settings like connection string. On your machine by default you have «Development» environment.

  3. You may use Error Handling middlewares for showing exceptions like

    app.UseDeveloperExceptionPage();
    

answered Sep 30, 2016 at 7:49

Set's user avatar

SetSet

46.3k21 gold badges131 silver badges147 bronze badges

1

Had the same issue. Here is the guide that helped me. Note, that I did not want to install the «Runtime» on the web server, but rather deploy all the necessary files as a stand alone app. Below are the steps in a more abbreviated form:

  1. On your local PC, Determine which version to publish based on your server. I was targeting Windows Server 2008, R2 which meant i needed to publish win7-x64. Open a command prompt in your project directory and run the command below:

    dotnet publish -c release -r win7-x64

    This creates a publish folder containing hundreds of dlls, an .exe, and web.config located here: binReleasenetcoreapp2.0publish

  2. On the web server with IIS, go to this landing page. Click the link for your desired version. Find the link for the Runtime and Hosting Bundle. Click to download and run.

  3. Restart IIS by running this from an elevated command prompt:

    net stop was

    net start w3svc

  4. Copy all of the files in your local publish folder to your desired application folder on the IIS server.

  5. On the server, Open IIS, and create a separate AppPool and Application like normal. For the AppPool, under Basic Settings, change the .NET Framework version to No Managed Code. Make sure your Application in IIS points to your desired folder and the proper AppPool.

  6. Test your web application in a browser.

Beakie's user avatar

Beakie

1,9382 gold badges19 silver badges45 bronze badges

answered May 10, 2018 at 14:16

James Lawruk's user avatar

James LawrukJames Lawruk

29.2k19 gold badges128 silver badges134 bronze badges

1

In my case, I got this because I hadn’t actually installed the latest ‘DotNetCore.2.0.0-WindowsHosting.exe’ on the windows server I was running it on… so it was working fine on my local machine in debug and error five hundy’ing on the server.

I had other non trivial to fix issues with the upgrade also… I’d advise avoiding it if you can.

answered Sep 4, 2017 at 13:14

David van Dugteren's user avatar

1

Mark333’s comment below solved my problem.

Quoting for easy reading:

«I’m using the normal publish provided by Visual Studio. And, I just
found out using the latest version of Hosting Bundle will fix the
issue. +1 on this
microsoft.com/net/download/dotnet-core/runtime-2.1.0-rc1»

I had to install for 1.1 since my app is a little older, but Hosting Bundle fixed it. In my case we deploy to a Docker image for our official environment, but when I want to do some testing locally I publish it and let my local IIS serve it up.

answered Aug 28, 2018 at 13:49

Matthew Allen's user avatar

Matthew AllenMatthew Allen

5292 gold badges7 silver badges13 bronze badges

Shiv Bachan's user avatar

answered Feb 21, 2019 at 13:00

Diego Venâncio's user avatar

Diego VenâncioDiego Venâncio

5,4392 gold badges47 silver badges67 bronze badges

2

I had installed DotNetCore.2.0.5-WindowsHosting.exe on a Windows 2008 R2 Standard machine and encountered the same http 500 error. Logging didn’t help (blank logs were generated — and Event Viewer logs were the generic ErrorCode = 0x80070002)

I had to do two things to solve my problem:

  1. Give Read rights to the ApplicationPoolIdentity user (EG: IIS APPPOOLAppPoolIdentityName) to the website directory and the application directory
  2. I had to install IIS ASP Core under Server Manager (this felt weird, but it worked!)

answered Jan 19, 2018 at 3:36

Rots's user avatar

RotsRots

5,4763 gold badges43 silver badges51 bronze badges

1

I had the same issue.

My problem was that my connection string to db was not set in appsettings.production.json

And the internal server error 500 was to vague error message.

Changing the stdoutLogEnabled = true did nothing to me so i was not seeing any information about the error.

answered Aug 12, 2018 at 7:01

Dongolo Jeno's user avatar

1

Make sure the App Pool has permissions to the folder where your app resides.

answered Nov 10, 2020 at 14:25

tno2007's user avatar

tno2007tno2007

1,81423 silver badges15 bronze badges

I experienced this issue. The problem was due to my local Sql Server instance. Remote connection were not allowed. So I manually restarted the SQL instance and my App restarted working fine.

answered Sep 20, 2019 at 7:13

DOUMBIA Mamadou's user avatar

I had similar issue after istalling dotnetcore-windowshosting using chocolatey while doing AWS ec2 instance bootstrapping.

When I checked my IIS modules AspNetCoreModule was missing.

This solved my issue. https://github.com/aspnet/IISIntegration/issues/434

I had to uninstall chocolatey package, restart machine and install it again.

Hope this helps!

answered Nov 1, 2019 at 5:31

prashant's user avatar

prashantprashant

2,1812 gold badges21 silver badges37 bronze badges

In my case, I created a .NET 5 single file output, and I was getting:

500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed.

The problem turned out to be that the EXE file was for some strange reason recognized as a virus by the protection software (CrowdStrike Falcon). Re-building without «single file output» option solved that problem.

answered Dec 13, 2021 at 17:29

Mr. TA's user avatar

Mr. TAMr. TA

5,17027 silver badges35 bronze badges

It also happens when you install dotnet-hosting-bundle/dotnet runtime beofore IIS.

In this case re-install dotnet-hosting-bundle/dotnet runtime.

answered Mar 22, 2022 at 7:36

gartenkralle's user avatar

gartenkrallegartenkralle

6361 gold badge11 silver badges21 bronze badges

To be able to see the excetion’s detail I just needed to change the ASPNETCORE_ENVIRONMENT to «Development» in the «IIS Express» profile in the launchSettings.json file. I aldo needed to create the corresponding appsettings.Development.json file to set the variables and data needed in my App. When the environment is Development net core send the detail exception by defaul. As we can read here in the official documentation.

answered Aug 10, 2022 at 14:44

Daniel Silva's user avatar

User-1158769213 posted

Hello,

I’m just starting with ASP.NET Core, and tried to deploy one today. I was faced with the above error when I tried to load it.

I started VS2017, created a new MVC Core site, and published. I didn’t change a thing, just published the site as it came out of the box.

I then copied the contents of the binReleasenetcoreapp2.2publish folder to my hosting company via FTP, and tried to load the site in a browser.

The hosting company installed Core 2.2 on the server. Do they need to do anything else? I only have control panel access (via SolidCP) to the server, not remote access, so there’s only so much I can do.

If I look in my control panel for the site, I see the following warning…

System.Web.Services.Protocols.SoapException: System.Web.Services.Protocols.SoapException: System.Web.Services.Protocols.SoapException: Server was unable to process request. —> System.Runtime.InteropServices.COMException: Filename: \?D:HostingSpacestestusertest.mydomain.co.ukwwwrootweb.config 
Error: 

at Microsoft.Web.Administration.Interop.AppHostWritableAdminManager.GetAdminSection(String bstrSectionName, String bstrSectionPath) 
at Microsoft.Web.Administration.Configuration.GetSectionInternal(ConfigurationSection section, String sectionPath, String locationPath) 
at SolidCP.Providers.Web.Iis.DirectoryBrowse.DirectoryBrowseModuleService.GetDirectoryBrowseSettings(ServerManager srvman, String siteId) 
at SolidCP.Providers.Web.IIs70.FillAppVirtualDirectoryFromIISObject(ServerManager srvman, WebAppVirtualDirectory virtualDir) 
at SolidCP.Providers.Web.IIs70.GetSite(String siteId) 
at SolidCP.Providers.Web.IIs80.GetSite(String siteId) 
at SolidCP.Server.WebServer.GetSite(String siteId) 
— End of inner exception stack trace — 
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) 
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) 
at SolidCP.Providers.Web.WebServer.GetSite(String siteId) 
at SolidCP.EnterpriseServer.WebServerController.GetWebSite(Int32 siteItemId) 
at SolidCP.EnterpriseServer.esWebServers.GetWebSite(Int32 siteItemId) 
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) 
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) 
at SolidCP.EnterpriseServer.esWebServers.GetWebSite(Int32 siteItemId) 
at SolidCP.Portal.WebSitesEditSite.BindWebSite()

The web.config file it mentions looks like this…

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".BasicCoreSite.dll" stdoutLogEnabled="false" stdoutLogFile=".logsstdout" hostingModel="InProcess" />
    </system.webServer>
  </location>
</configuration>
<!--ProjectGuid: 2fbe438c-a8b2-4b5b-8224-eb5dfcb62107-->

I tried changing the value of stdoutLogEnabled to «true» to see if that would give me a log file, but I couldn’t see anything appear.

Anyone any idea what went wrong? The hosting company don’t know much about Core, so can’t help.

Thanks for any help you can give.

Содержание

  1. Handle errors in ASP.NET Core web APIs
  2. Developer Exception Page
  3. Exception handler
  4. Use exceptions to modify the response
  5. Validation failure error response
  6. Client error response
  7. Default problem details response
  8. Problem details service
  9. Customize problem details with CustomizeProblemDetails
  10. Implement ProblemDetailsFactory
  11. Use ApiBehaviorOptions.ClientErrorMapping
  12. Additional resources
  13. Developer Exception Page
  14. Exception handler
  15. Use exceptions to modify the response
  16. Validation failure error response
  17. Client error response
  18. Implement ProblemDetailsFactory
  19. Use ApiBehaviorOptions.ClientErrorMapping
  20. Custom Middleware to handle exceptions
  21. Produce a ProblemDetails payload for exceptions
  22. Additional resources
  23. Developer Exception Page
  24. Exception handler
  25. Use exceptions to modify the response
  26. Validation failure error response
  27. Client error response
  28. Implement ProblemDetailsFactory
  29. Use ApiBehaviorOptions.ClientErrorMapping
  30. Custom Middleware to handle exceptions

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.

Источник

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.

We are going to explore four potential reasons why your ASP.NET Core Application is not working in IIS.

Now the reason why I’m writing this article is because I’ve had a few people get in contact with me as a result of my article «How to Publish an ASP.NET Core & React SPA to IIS».

They were saying they still couldn’t get their ASP.NET Core application to work in IIS, despite following the recommendations in that article.

So, that’s explore the reasons why this might be the case and come up with some rememdies.

Problem #1: Permissions

So you’ve published your ASP.NET Core application. You’ve set up a website in IIS pointing to your published folder.

Tried to run the application. And then IIS throws an error that reads as follows:

HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.

Config Error: Cannot read configuration file due to insufficient permissions

500.19 Error when Running an ASP.NET Core Application in IIS

500.19 Error when Running an ASP.NET Core Application in IIS

This error is because IIS does not have the correct permissions to render your ASP.NET Core application.

In Windows 10, you need to give full access to the IIS_IUSRS group in the path where you are hosting your ASP.NET Core application in IIS.

Give IIS_IUSRS Full Control to your ASP.NET Core Application in IIS
In Windows 10, give IIS_IUSRS Full Control to your ASP.NET Core Application in IIS

This should resolve your issue.

However, what if that group is not there? Or it doesn’t resolve the issue?

If the group is not there, you can add the Users group to the folder that’s running your ASP.NET Core application in IIS. And give it full permission. That should at least get your application working.

But, it might be that you’ve changed the identity of the application pool in IIS. You might be running your IIS application from a different user.

In which case, in IIS, go to Application Pools and click on the pool running your application.

Go to Advanced Settings… and navigate to Process Model and Identity.

Check the Application Pool Identity in IIS when running an ASP.NET Core Application

Check the Application Pool Identity in IIS when running an ASP.NET Core Application

If you are using a Custom Account, you will probably need to give full permissions to that account as well.

Problem #2: Installing ASP.NET Core Runtime

If you are running an ASP.NET Core application, you must install ASP.NET Core Runtime onto the machine that is running your application through IIS.

You can download ASP.NET Core Runtime from Microsoft’s ASP.NET Core website. It will give you different installers dependent on which operating system you are using.

For IIS, it’s recommended that you install the Hosting Bundle. Not only does this install ASP.NET Core Runtime, but also additional support for IIS runtime support.

Download ASP.NET Core Runtime Hosting Bundle for Windows

For IIS, download the Hosting Bundle from the Windows OS to download ASP.NET Core Runtime & additional IIS runtime support

Problem #3: Different ASP.NET Core Runtime Version

It’s easily done. You’ve successfully deployed your ASP.NET Core application onto IIS and everything is fine.

That is until you upgrade your ASP.NET Core version. You try and deploy it to IIS and then you get a 500 error.

Here is an example of trying to run an ASP.NET Core 3 application with ASP.NET Core Runtime 1 installed.

The error reads:

HTTP Error 500.21 - Internal Server Error
Handler "aspNetCore" had a bad module "AspNetCoreModuleV2" in its moudle list

500.21 Error when Running an ASP.NET Core 3 Application with ASP.NET Core Runtime 1

500.21 Error when Running an ASP.NET Core 3 Application with ASP.NET Core Runtime 1

Now I must stress that you might not get any error when you upgrade your ASP.NET Core version for your application without upgrading your ASP.NET Core Runtime.

But, it’s worth keeping it up to date.

Problem #4: A Runtime Error With Your Application

This one was raised by Chaker Aich on my YouTube channel.

So you’ve tried all these solutions, but you are still getting a 500 error.

This one is more specific as it relates to a start up failure.

HTTP Error 500.30 - ANCM In-Process Start Failure

500.30 Error when Running an ASP.NET Core Application in IIS

500.30 Error when Running an ASP.NET Core Application in IIS

This is a problem with your ASP.NET Core application rather than IIS. There is a runtime error.

First, check that it runs locally on your machine. Assuming you are using Visual Studio, open the application in Visual Studio and run the application.

If it throws an error, you will know the reason why you are getting a 500.30 error in IIS.

However, if it’s working fine, there is probably something wrong with the IIS environment. Maybe the server cannot see the database? Or maybe, there is something that hasn’t been installed on the server?

To help you identify the issue, you can turn on log files.

In the directory that is running your ASP.NET Core application in IIS, you should have a web.config file.

In there, you should have an aspNetCore tag with a stdoutLogEnabled and stdoutLogFile attribute.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".RoundTheCode.ReactSignalR.dll" stdoutLogEnabled="false" stdoutLogFile=".logsstdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>

Now the stdoutLogEnabled attribute should be set to false. By setting that to true, you should be able log the runtime error that you are getting in your application.

The log files are stored in the folder path that is contained in the stdoutLogFile attribute.

Still Stuck?

If you are not quite following the solutions to the fixes, you can watch us demonstrate these errors and applying fixes.

We go ahead and publish our ASP.NET Core application to a folder, ready for IIS to host.

Afterwards, we set the appropriate permissions that IIS needs to render your ASP.NET Core application.

Then, we go ahead and install the ASP.NET Core Runtime onto our machine.

Lastly, we demonstrate the checks you can use to deal with any runtime errors you are getting when running your ASP.NET Core application in IIS.

Issue:

Server Error
500 - Internal server error.
There is a problem with the resource you are looking for, and it cannot be displayed.

Or

HTTP Error 502.5 - Process Failure


Common causes of this issue: 
• The application process failed to start 
• The application process started but then stopped 
• The application process started but failed to listen on the configured port


Troubleshooting steps: 
• Check the system event log for error messages 
• Enable logging the application process' stdout messages 
• Attach a debugger to the application process and inspect


For more information visit:  https://go.microsoft.com/fwlink/?LinkID=808681

Browser showing 500 Internal Server Error after published my ASP.Net Core application to the Windows IIS web server.

Environment:

Windows 2016 Server with IIS, ASP.NET Core version 2.0.7

Resolution:

Make sure “Hosting Bundle Installer” is installed which includes Windows Server Hosting and .Net Core Runtime version of your choice. You can do this even you had installed either one of them. These two pieces of software are needed to run ASP.Net Core Application.

Option 1:-

1) install “Hosting Bundle Installer” file version 2.0.7 from https://www.microsoft.com/net/download/dotnet-core/runtime-2.0.7 or latest version

https://www.microsoft.com/net/download/dotnet-core/runtime-2.0.7

2) browse to your web site and see if it fixes the issue

Notes:

  1. You can always download the latest version of .Net Core Runtime from https://www.microsoft.com/net/download/all
  2. Double check if you have installed both software under Program and Features
    Hosting Bundle Installer version 2.0.6
  3. To enable logging the application process’ stdout messages, open file web.config and change stdoutLogEnabled attribute from false to true as shown below
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <system.webServer>
        ...
        <aspNetCore processPath="dotnet" arguments=".Ms.App.Web.dll" stdoutLogEnabled="true" stdoutLogFile=".logsstdout" />
      </system.webServer>
    </configuration>
  4. To see which version you need, you could check a file [YourProjName].runtimeconfig.json
    {
      "runtimeOptions": {
        "tfm": "netcoreapp2.0",
        "framework": {
          "name": "Microsoft.AspNetCore.App",
          "version": "2.0.6"
        }
      }
    }

Понравилась статья? Поделить с друзьями:
  • Asp net application error
  • Asp net 1309 ошибка
  • Asp mvc error 500
  • Asmmap64 sys как исправить ошибку
  • Asmb8 ikvm java error