An error occurred while starting the application как исправить

After publishing an ASP.NET Web App, I’m trying to host the website on my local server. However, when I start it up, it gives me this error in my browser:

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

How can I debug what this error is? The website works (both Debug and Release configurations) when starting using IISExpress and «web» in Visual Studio.

I am using the Development environment, and I have already specified app.UseDeveloperExceptionPage();.

I have followed the instructions here to deploy to IIS.

I’ve also tried the suggestion offered here (re-publishing with «Delete all existing files prior to publish» selected). (The OP there has a slightly different error, so that’s why I’m posting a new question.)

I’ve looked for hours on the internet, but there doesn’t seem to be much content about it. Any ideas?

I am on Windows 7, using ASP.NET 5 RC1.

Community's user avatar

asked Feb 26, 2016 at 23:42

painiyff's user avatar

3

You should set the stdoutLogEnabled=true in the web.config file to see the actual error that is happening. You can direct where these files are written with the stdoutLogFile argument; the screenshot example below writes to stdoutLogFile=".logsstdout". (You should ensure the directory exists; the app won’t create it)

As for not being able to find the proper config file yes the default environment is production. It is set to development explicitly in visual studio in the project properties.

Update: In AspNetCore RTM the module is called aspnetCore under the system.webServer node in web.config. Also, as @ErikE pointed out in comments, the web.config is now located in the root of the project and not under wwwroot as in previous releases.

enter image description here

Nate Anderson's user avatar

Nate Anderson

17.6k18 gold badges99 silver badges133 bronze badges

answered Feb 29, 2016 at 23:45

Muqeet Khan's user avatar

Muqeet KhanMuqeet Khan

2,0741 gold badge18 silver badges28 bronze badges

7

This error also occurs when you are attempting a database connection from the startup (eg for seeding) and it fails on the deployment server due to insufficent previleges at the database server.

answered Jul 1, 2016 at 7:49

Andre's user avatar

AndreAndre

1311 silver badge5 bronze badges

2

This error occurs under several conditions. In my situation, I did not have the database connection string set correctly. I fixed it in Visual Studio 2017 as follows:

1) Right-click project, select Publish, open the Publish page in main area.

2) Select the Publish tab on the left

3) Under Summary section, there’s a «Settings…» link. Click it. This opens the Publish dialog.

4) Click Settings tab on the left.

5) Expand File Publish Options, check «Remove additional files at destination»

6) Expand Databases, check «Use this connection string at runtime» (This was pre-populated with my Azure SQL connection string based on how I originally set up my publish options)

7) Expand Entity Framework Migrations, check «Apply this migration on publish» (Again, connection string was pre-populated)

8) Click Save

9) Publish

10) Cross your fingers

0

I was getting same issue.
Checked the log and found that, inside config.json => HostConfig FileUpload path (pointing local drive) was incorrect. and creating problem to restart application.
Conclusions: there might be multiple reason for this issue.

answered May 24, 2022 at 7:40

Jagram singh's user avatar

The Problem: most likely this error is due to insufficient privileges for the Application Pool Identities. To find out:

Go to windows Task Manager and under Details tab / Processes (Depending on Windows OS) look for w3wp.exe and under User name look for your application (<App_Pool_Name> usually DefaultAppPool) running there as an IIS Worker Process. If your app is not listed there, then the App has insufficient privileges with your database.

To Fix it: do the following and give full access to your App:

Go to your SQL Server Management Studio and Login as Administrator open Security > Logins > right click Logins and add a New Login:

Under General:

  • for Login Name: Enter IIS APPPOOL<App_Pool_Name> usually DefaultAppPool

  • for Default Database: point to <Your_App_Database>

Under User Mapping:

  • on the box Users mapped to this login:

    Check the box to Map to <Your_App_Database>

    -Under user Enter IIS APPPOOL<App_Pool_Name>usually DefaultAppPool

    -Under Default Schema Enter dbo

  • on the box Database role membership for: <Your_App_Database>

    Check the following boxes: db_datareader, db_datawriter, and public

Click OK

Now try to access your App and it should work!!!

answered Oct 24, 2017 at 16:24

Jacman's user avatar

JacmanJacman

1,4283 gold badges20 silver badges31 bronze badges

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.

Перейти к контенту

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.

After publishing an ASP.NET Web App, I’m trying to host the website on my local server. However, when I start it up, it gives me this error in my browser:

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

How can I debug what this error is? The website works (both Debug and Release configurations) when starting using IISExpress and «web» in Visual Studio.

I am using the Development environment, and I have already specified app.UseDeveloperExceptionPage();.

I have followed the instructions here to deploy to IIS.

I’ve also tried the suggestion offered here (re-publishing with «Delete all existing files prior to publish» selected). (The OP there has a slightly different error, so that’s why I’m posting a new question.)

I’ve looked for hours on the internet, but there doesn’t seem to be much content about it. Any ideas?

I am on Windows 7, using ASP.NET 5 RC1.

Community's user avatar

asked Feb 26, 2016 at 23:42

painiyff's user avatar

3

You should set the stdoutLogEnabled=true in the web.config file to see the actual error that is happening. You can direct where these files are written with the stdoutLogFile argument; the screenshot example below writes to stdoutLogFile=".logsstdout". (You should ensure the directory exists; the app won’t create it)

As for not being able to find the proper config file yes the default environment is production. It is set to development explicitly in visual studio in the project properties.

Update: In AspNetCore RTM the module is called aspnetCore under the system.webServer node in web.config. Also, as @ErikE pointed out in comments, the web.config is now located in the root of the project and not under wwwroot as in previous releases.

enter image description here

The Red Pea's user avatar

The Red Pea

16.6k18 gold badges96 silver badges127 bronze badges

answered Feb 29, 2016 at 23:45

Muqeet Khan's user avatar

Muqeet KhanMuqeet Khan

2,0341 gold badge18 silver badges28 bronze badges

7

This error also occurs when you are attempting a database connection from the startup (eg for seeding) and it fails on the deployment server due to insufficent previleges at the database server.

answered Jul 1, 2016 at 7:49

Andre's user avatar

AndreAndre

1311 silver badge5 bronze badges

2

This error occurs under several conditions. In my situation, I did not have the database connection string set correctly. I fixed it in Visual Studio 2017 as follows:

1) Right-click project, select Publish, open the Publish page in main area.

2) Select the Publish tab on the left

3) Under Summary section, there’s a «Settings…» link. Click it. This opens the Publish dialog.

4) Click Settings tab on the left.

5) Expand File Publish Options, check «Remove additional files at destination»

6) Expand Databases, check «Use this connection string at runtime» (This was pre-populated with my Azure SQL connection string based on how I originally set up my publish options)

7) Expand Entity Framework Migrations, check «Apply this migration on publish» (Again, connection string was pre-populated)

8) Click Save

9) Publish

10) Cross your fingers

0

I was getting same issue.
Checked the log and found that, inside config.json => HostConfig FileUpload path (pointing local drive) was incorrect. and creating problem to restart application.
Conclusions: there might be multiple reason for this issue.

answered May 24, 2022 at 7:40

Jagram singh's user avatar

The Problem: most likely this error is due to insufficient privileges for the Application Pool Identities. To find out:

Go to windows Task Manager and under Details tab / Processes (Depending on Windows OS) look for w3wp.exe and under User name look for your application (<App_Pool_Name> usually DefaultAppPool) running there as an IIS Worker Process. If your app is not listed there, then the App has insufficient privileges with your database.

To Fix it: do the following and give full access to your App:

Go to your SQL Server Management Studio and Login as Administrator open Security > Logins > right click Logins and add a New Login:

Under General:

  • for Login Name: Enter IIS APPPOOL<App_Pool_Name> usually DefaultAppPool

  • for Default Database: point to <Your_App_Database>

Under User Mapping:

  • on the box Users mapped to this login:

    Check the box to Map to <Your_App_Database>

    -Under user Enter IIS APPPOOL<App_Pool_Name>usually DefaultAppPool

    -Under Default Schema Enter dbo

  • on the box Database role membership for: <Your_App_Database>

    Check the following boxes: db_datareader, db_datawriter, and public

Click OK

Now try to access your App and it should work!!!

answered Oct 24, 2017 at 16:24

Jacman's user avatar

JacmanJacman

1,4083 gold badges20 silver badges31 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. :)

Вопрос:

Я попытался опубликовать приложение ASP.NET Core на Windows Server 2008 R2, но я получаю эту ошибку: “Произошла ошибка при запуске приложения”.

Без описания!

Что я могу сделать?

Лучший ответ:

Ответ №1

  1. попробуйте включить ведение журнала в web.config

<aspNetCore stdoutLogEnabled = “true” stdoutLogFile = “.logsstdout”/>

  1. если нет журналов, проверьте средство просмотра событий, что-то вроде:

Не удалось создать stdoutLogFile C:inetpub… ErrorCode = -2147024891.

  1. Попробуйте настроить сайт на другом диске, например D:inetpubwebsite

в моем случае он отлично работает с другого диска, но он не работает с C:inetpubwebsite. Я полагаю, что это своего рода проблема с разрешениями безопасности.

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

Хотя я Администратор на ПК и других веб-сайтах в.NET Framework 4.7.1 работает с C:inetpubна главном сайте asp.net есть проблема

Ответ №2

Это не настоящая ошибка. Вы должны найти настоящую ошибку. Чтобы увидеть реальную ошибку, сделайте следующее. Помните, что вы должны отменить эти изменения, как только вы выявите проблему и исправите ее. Вы не должны показывать реальную ошибку конечным пользователям.

В вашей среде разработки, попробуйте добавить/обновить это в web.config, чтобы увидеть реальную ошибку

<aspNetCore processPath=".MyApplication.exe" arguments="" stdoutLogEnabled="false" stdoutLogFile=".logsstdout">
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
</environmentVariables>
</aspNetCore>

В вашем program.cs добавьте/обновите ниже, чтобы увидеть реальную ошибку

public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.CaptureStartupErrors(true)
.UseSetting("detailedErrors", "true")
.UseStartup<Startup>()
.Build();

Ответ №3

В Althouth есть много вещей, которые могут пойти не так, как надо, и надлежащим образом – фактически устранить ошибку, мой случай был проще:

Я забыл настроить выходной путь выпуска для Swagger

Вы можете это сделать, выполнив следующие шаги:

  1. Щелкните правой кнопкой мыши свой проект
  2. Щелкните Properties
  3. Перейдите на вкладку ” Build
  4. И в разделе ” Output ” установите флажок в XML documentation file.

Это автозаполняет путь XML файлом, но вы можете изменить его на все, что захотите.

Я копирую-вставляю решение из https://mycodepad.wordpress.com/2018/08/23/publishing-asp-net-core-an-error-occurred-while-starting-the-application/

MadCrach

0 / 0 / 0

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

Сообщений: 56

1

19.04.2020, 19:22. Показов 6972. Ответов 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

15564 / 12541 / 4981

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

Сообщений: 25,458

Записей в блоге: 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

  • 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. :)

Понравилась статья? Поделить с друзьями:
  • Как найти характерный размер
  • Как составить программу с оператором цикла
  • Как исправить прямоугольное лицо
  • Как исправить неполадки с интернетом на компьютере
  • Как найти пьесу для театра