An error occurred while starting the application net core

The Problem If you’ve ever seen this message when hitting your ASP.NET Core app: “An error occurred while starting the application.  .NET Framework | Microsoft.As…

Skip to content

The Problem

If you’ve ever seen this message when hitting your ASP.NET Core app:

“An error occurred while starting the application.  .NET Framework <version number> | Microsoft.AspNetCore.Hosting version <version number> | Microsoft Windows <version number>”

It looks a little something like this:

2017-04-07_15-20-55

What Happened?

It basically means something really bad happened with your app.  Some things that might have gone wrong:

  1. You might not have the correct .NET Core version installed on the server.
  2. You might be missing DLL’s
  3. Something went wrong in your Program.cs or Startup.cs before any exception handling kicked in

Event Viewer (probably) won’t show you anything

If you’re running on Windows and behind IIS, you might immediately go to the Event Viewer to see what happened based on your previous ASP.NET knowledge.  You’ll notice that the error is not there.  This is because Event Logging must be wired up explicitly and you’ll need to use the Microsoft.Extensions.Logging.EventLog package, and depending on the error, you might not have a chance to even catch it to log to the Event Viewer.

How to figure what happened (if running on IIS)

Instead of the Event Viewer, if you’re running behind IIS, we can log the request out to a file.  To do that:

  1. Open your web.config
  2. Change stdoutLogEnabled=true
  3. Create a logs folder
    1. Unfortunately, the AspNetCoreModule doesn’t create the folder for you by default
      1. If you forget to create the logs folder, an error will be logged to the Event Viewer that says: Warning: Could not create stdoutLogFile \?YourPathlogsstdout_timestamp.log, ErrorCode = -2147024893.
    2. The “stdout” part of  the value “.logsstdout” actually references the filename not the folder.  Which is a bit confusing.
  4. Run your request again, then open the logsstdout_*.log file


Note – you will want to turn this off after you’re done troubleshooting, as it is a performance hit.

So your web.config’s aspNetCore element should look something like this

 <aspNetCore processPath=”.YourProjectName.exe” stdoutLogEnabled=”true” stdoutLogFile=”.logsstdout” />

Doing this will log all the requests out to this file and when the exception occurs, it will give you the full stack trace of what happened in the logsstdout_*.log file

2017-04-07_15-35-45.png

2017-04-07_15-42-40.png

Hope this helps.  This happened to me a friend of mine.  A friend.  Yep.  Definitely not me.  My apps would never bomb.

I have upgraded asp.net core 1.1 to an asp.net core 2. It runs fine on the local server, but when I try to deploy it to an Azure hosted web app, I received the error:

An error occurred while starting the application. .NET Core

4.6.00001.0 X86 v4.0.0.0 | Microsoft.AspNetCore.Hosting version 2.0.0-rtm-26452 | Microsoft Windows 6.2.9200

enter image description here

Any ideas?

Melchia's user avatar

Melchia

21.5k21 gold badges97 silver badges113 bronze badges

asked Nov 6, 2017 at 10:22

Arvind Sisara's user avatar

4

Please add ASPNETCORE_DETAILEDERRORS = true in app settings of your app, restart it and see the detailed error next time you load the url.
That will help you fix it.

For example, error in my case was that I didn’t have the managed identity of my API App configured to access the Key Vault to get the storage account and Cosmos DB keys. I used startup to inject the configured storage and cosmos db objects hence it was failing the moment I was starting my app.

When you’ve fixed the startup issue, don’t forget to remove this setting as leaving it on could expose information about how the application works to visitors in the event of another error.

Captain Obvious's user avatar

answered Nov 6, 2017 at 11:41

Suneet Nangia's user avatar

Suneet NangiaSuneet Nangia

1,6401 gold badge11 silver badges6 bronze badges

7

Got my tips from https://scottsauber.com/2017/04/10/how-to-troubleshoot-an-error-occurred-while-starting-the-application-in-asp-net-core-on-iis/

  1. Open your web.config
  2. Change stdoutLogEnabled=true
  3. Create a logs folder
    Unfortunately, the AspNetCoreModule doesn’t create the folder for you by default
    If you forget to create the logs folder, an error will be logged to the Event Viewer that says: Warning: Could not create stdoutLogFile ?YourPathlogsstdout_timestamp.log, ErrorCode = -2147024893.
    The “stdout” part of the value “.logsstdout” actually references the filename not the folder. Which is a bit confusing.
    Run your request again, then open the logsstdout_*.log file

Note – you will want to turn this off after you’re done troubleshooting, as it is a performance hit.

So your web.config’s aspNetCore element should look something like this

<aspNetCore processPath=”.YourProjectName.exe” stdoutLogEnabled=”true” stdoutLogFile=”.logsstdout” />

touhid udoy's user avatar

touhid udoy

3,9152 gold badges17 silver badges30 bronze badges

answered Nov 19, 2018 at 20:11

NoloMokgosi's user avatar

NoloMokgosiNoloMokgosi

1,65116 silver badges10 bronze badges

3

Enable DetailedErrorsKey in the Program.cs so you can figure it out what’s happening.

WebHost.CreateDefaultBuilder(args)
    .UseSetting(WebHostDefaults.DetailedErrorsKey, "true")

answered Jul 21, 2019 at 19:58

Masoud Darvishian's user avatar

You can obtain more details by enabling ASPNETCORE_DETAILEDERRORS = true:

go to your Azure Dashboard -> Your App Service

In your application Settings (in the left hand sidebar) -> scroll down to configuration which is a key:value pair of settings, input the above.
Restart your web app.

answered Jul 16, 2019 at 15:22

Melchia's user avatar

MelchiaMelchia

21.5k21 gold badges97 silver badges113 bronze badges

Try executing the application by firing the command

dotnet myapplicationname.dll

This shall throw the startup errors and may help you narrow down the error.

answered Sep 11, 2019 at 20:30

Sunil Johnson's user avatar

1

I managed to solve the problem myself and I hope this solution might help someone.

First, I have set log folder on the Azure server and find issue with more details.
I forgot some database changes in SQL.Update database changes and run it’s working fine now.

answered Nov 8, 2017 at 6:42

Arvind Sisara's user avatar

Arvind SisaraArvind Sisara

8512 gold badges7 silver badges13 bronze badges

2

I was able to discover my exceptions for this error by starting the app from it’s published executable.

To try this locally, you can right click on the web project, click publish, and then publish it to a folder. There should be an executable in the folder of the same name as the project. Run that and it should show exceptions in the console.

answered May 20, 2019 at 15:07

farlee2121's user avatar

farlee2121farlee2121

2,7313 gold badges28 silver badges40 bronze badges

  • Remove From My Forums
  • Question

  • User1164381444 posted

    I’ve been building an ASP.NET Core app (1.1) and deploying it to an Azure instance I’ve had for a while.

    Everything was working fine, then suddenly I deploy and get this error when I navigate to the site:

    An error occurred while starting the application.
    
    .NET Core X86 v4.1.1.0    |   Microsoft.AspNetCore.Hosting version 1.1.1    |    Microsoft Windows 6.2.9200    |   Need help? 

    The publish succeeds (as it has) in the past.

    I had read via this post on StackOverflow that it’s helpful to connect via FTP and delete everything in «Site/wwwroot» but when I attempted to FTP to the instance I was unable to connect.

    Any ideas on how to troubleshoot this instance?

    I’d be fine with a way to «reset» it because it’s not in production yet and I can just deploy my code to it and be back where I want to be. :)

An error occurred while starting the application. .NET Core | Microsoft.AspNetCore.Hosting version | Microsoft Windows

Hi,
In this post, I would like to explain how we can handle the following error that we usually get when hosting Asp.Net core application using IIS.

** An error occurred while starting the application. .NET Core | Microsoft.AspNetCore.Hosting version | Microsoft Windows **

An error occurred while starting the application.

.NET Core X86 v4.1.1.0    |   Microsoft.AspNetCore.Hosting version 1.1.1    |    Microsoft Windows 6.2.9200    |   Need help?

I was getting above error after publishing my code to a remote server and hosting it using IIS.

I was actually clueless and tried to find out what was the actual error, this particular message looks generic and there might be something that is actually causing this issue.

I tried looking at EventLogs but still, I don’t see any error message logging over there.

How to log error message in Asp.Net Core

  1. Go to Projects Web.Config file and try to enable error by setting true to “stdoutLogEnabled” property
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="true" stdoutLogFile=".logsstdout">
      <environmentVariables />
    </aspNetCore>
  1. Also in the config file, we see the location where errors are supposed to be written.
  2. So by default Asp.Net core doesn’t create these folders, In our case ** “logsstdout”. So go and create a folder by name **“logs”
  3. Go to Visual studio proj and add a folder by name “logs” at the root level and add a sample.txt file(this can be an empty one.. Just because if the content is empty then we will not get this folder in Published files)
  4. Now publish the project and make sure that we have logs folder present.
  5. Now when we run the application and if there are any errors, It will be logged in logs folder in server and that helps us in identifying what the actual error is.

In my case the error was something related to Entityframework and sqllite DB

Application startup exception: Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 14: 'unable to open database file'.
   at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)
   at Microsoft.Data.Sqlite.SqliteConnection.Open()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal.SqliteRelationalConnection.Open(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal.SqliteDatabaseCreator.Create()
   at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureCreated()
   at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureCreated()

I was getting this error because I am trying to create a SqLite DB in a subfolder and again ASP.Net core was not able to create subfolder. So I manually created the folder and it was resolved.

optionsBuilder.UseSqlite(@"Data Source=C:PavanMyDatabase.db");

Thanks,
Pavan Kumar Aryasomayajulu

Hello,

There is a MVC web app that we are attempting to publish to IIS on Windows Server 2008 R2 SP 1. Previously we were deploying our web app using .NET Core RC1 and .NET Core 1.0 fine on the same server and it started and ran without such issues.

However having upgraded to .NET Core 1.1 we are getting some issues getting the application to run on the same server. We have installed the .NET Core 1.1 runtime on the server and configured the web app in IIS as documented here: https://docs.microsoft.com/en-us/aspnet/core/publishing/iis

After deploying to the server and attempting to run it we were first getting this error in the browser window:

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: http://go.microsoft.com/fwlink/?LinkID=808681

After some research we changed the web.config on the deployed web app as follows:

From:

<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".logsstdout" forwardWindowsAuthToken="false"/>

To:

<aspNetCore processPath="dotnet" arguments=".MyWebApp.dll" stdoutLogEnabled="true" stdoutLogFile=".logsstdout" forwardWindowsAuthToken="false"/>

Now we get this error in the browser window:

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 6.1.7601 S    |   Need help? 

It also started error logging to the /logs/ folder. The error from these logs is:

Application startup exception: System.DllNotFoundException: Unable to load DLL 'api-ms-win-core-registry-l1-1-0.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
   at Interop.mincore.RegOpenKeyEx(SafeRegistryHandle hKey, String lpSubKey, Int32 ulOptions, Int32 samDesired, SafeRegistryHandle& hkResult)
   at Microsoft.Win32.RegistryKey.InternalOpenSubKeyCore(String name, RegistryRights rights, Boolean throwOnPermissionFailure)
   at Microsoft.AspNetCore.DataProtection.RegistryPolicyResolver.ResolveDefaultPolicy()
   at Microsoft.Extensions.DependencyInjection.DataProtectionServices.<GetDefaultServices>d__0.MoveNext()
   at Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions.TryAdd(IServiceCollection collection, IEnumerable`1 descriptors)
   at Microsoft.Extensions.DependencyInjection.DataProtectionServiceCollectionExtensions.AddDataProtection(IServiceCollection services)
   at Microsoft.Extensions.DependencyInjection.AuthenticationServiceCollectionExtensions.AddAuthentication(IServiceCollection services)
   at Microsoft.Extensions.DependencyInjection.IdentityServiceCollectionExtensions.AddIdentity[TUser,TRole](IServiceCollection services, Action`1 setupAction)
   at MyWebApp.Startup.ConfigureServices(IServiceCollection services) in C:MyWebAppStartup.cs:line 49
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
Hosting environment: Production
Content root path: C:inetpubwwwrootmywebapp
Now listening on: http://localhost:47113
Application started. Press Ctrl+C to shut down.

The error that it mentions «at MyWebApp.Startup.ConfigureServices(IServiceCollection services) in C:MyWebAppStartup.cs:line 49» refers to the line below in Startup.cs:

services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

ApplicationDbContext was auto-generated by Visual Studio 2015 (Update 3) for the ASP.NET authentication and login functionality. This line of code was commented out and the web app re-deployed, but then it gave the same error for this line in Startup.cs:

Microsoft Visual C++ 2015 Redistributable (x64) 14.0.24212 is installed on the server. This web app runs fine without such errors locally.

Any ideas as to what is causing this and how it could be resolve? Thank you.

MadCrach

0 / 0 / 0

Регистрация: 09.12.2017

Сообщений: 56

1

19.04.2020, 19:22. Показов 6347. Ответов 8

Метки нет (Все метки)


Привет, изучаю ASP.Net Core, переписал код с урока но ошибку почему то выдает такую

XML
1
2
Серьезность  Код  Описание    Проект    Файл    Строка    Состояние подавления
Предупреждение    MVC1005 Using 'UseMvc' to configure MVC is not supported while using Endpoint Routing. To continue using 'UseMvc', please set 'MvcOptions.EnableEndpointRouting = false' inside 'ConfigureServices'.    ASP.CORE    ASP.COREASP.COREStartup.cs    37  Активные

и не работает сайт
вот код

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
 
namespace ASP.CORE
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
 
        }
 
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
 
            app.UseRouting();
 
            
 
            app.UseStaticFiles();
 
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "/",
                    template: "{controller=Home}/{action=Index}");
            });
 
  
        }
    }
}

Подскажите что не так работает

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



OwenGlendower

Администратор

Эксперт .NET

15248 / 12287 / 4904

Регистрация: 17.03.2014

Сообщений: 24,883

Записей в блоге: 1

19.04.2020, 23:19

2

MadCrach, разные виды роутинга конфликтовать начинают. Думаю нужно убрать строку

C#
1
app.UseRouting();



0



FordRelak

7 / 5 / 2

Регистрация: 03.11.2018

Сообщений: 20

20.04.2020, 11:58

3

Лучший ответ Сообщение было отмечено MadCrach как решение

Решение

MadCrach, может помочь еще это. В ConfigureServices напиши

C#
1
services.AddMvc(o=>o.EnableEndpointRouting  = false);



1



MadCrach

0 / 0 / 0

Регистрация: 09.12.2017

Сообщений: 56

21.04.2020, 16:38

 [ТС]

4

Спасибо помогло,
скажите а почему я новый марширут не могу зарегить

C#
1
2
3
4
5
6
7
8
9
10
app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "/",
                    template: "{controller=Home}/{action=Index}");
 
                routes.MapRoute(
                   name: "/test",
                   template: "{controller=Home}/{action=Test}");
            });



0



FordRelak

7 / 5 / 2

Регистрация: 03.11.2018

Сообщений: 20

21.04.2020, 16:54

5

MadCrach, Оставь

C#
1
2
3
routes.MapRoute(
                    name: "/",
                    template: "{controller=Home}/{action=Index}");

А в представлении будешь через asp-action = «Test» запускать функцию



0



0 / 0 / 0

Регистрация: 09.12.2017

Сообщений: 56

21.04.2020, 16:56

 [ТС]

6

Цитата
Сообщение от FordRelak
Посмотреть сообщение

А в представлении будешь через asp-action = «Test» запускать функцию

я создал , в котролее HomeController метод Test



0



7 / 5 / 2

Регистрация: 03.11.2018

Сообщений: 20

21.04.2020, 16:57

7

MadCrach, так а представление есть?



0



0 / 0 / 0

Регистрация: 09.12.2017

Сообщений: 56

21.04.2020, 17:02

 [ТС]

8

Цитата
Сообщение от FordRelak
Посмотреть сообщение

MadCrach, так а представление есть?

я возращаю просто строку



0



7 / 5 / 2

Регистрация: 03.11.2018

Сообщений: 20

21.04.2020, 17:19

9

MadCrach, написал в лс. Это уже другой вопрос и для него лучше бы создать другую тему



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

21.04.2020, 17:19

9

Понравилась статья? Поделить с друзьями:
  • An error occurred while starting service hvc
  • An error occurred while starting roblox файл занят другим процессом
  • An error occurred while starting roblox процесс не может получить доступ к файлу
  • An error occurred while starting roblox не устанавливается
  • An error occurred while starting roblox не удается найти указанный файл