簡體   English   中英

do.net 意外退出 - 在 ASP.NET Core 中創建新項目后

[英]dotnet quit unexpectedly - after creating new project in ASP.NET Core

我在使用 ASP.NET Core(3.1 版和 5.0 版)創建新的 MVC 項目時收到此警告:

do.net 意外退出

因為警告描述確實告訴我問題出在哪里,所以我不知道從哪里開始。

這是我的Startup.cs文件:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        
    }

    // 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.UseMigrationsEndPoint();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
        });
    }
}

在此處輸入圖像描述

我錯過了什么嗎?

有多種情況會收到此警告。 可以在文件Startup.csConfigureServices方法中修復一些問題。

如果您使用的是 Visual Studio,則可以打開Application Output選項卡(View -> Other Windows -> Application Output)

如果您收到一些消息,例如:

情況1:

未處理的異常。 System.InvalidOperationException:無法找到所需的服務。 請通過在應用程序啟動代碼中對“ConfigureServices(...)”的調用中調用“IServiceCollection.AddAuthorization”來添加所有必需的服務。

修復:調用services.AddAuthorization(); ConfigureServices方法中的方法。

注意:不同於services.AddAuthentication(); (當您想啟用某些服務時可以使用此服務,例如:使用 Facebook/Google/Twitter 登錄...)


案例二:

未處理的異常。 System.InvalidOperationException:無法找到所需的服務。 請通過在應用程序啟動代碼中對“ConfigureServices(...)”的調用中調用“IServiceCollection.AddControllers”來添加所有必需的服務。

修復:調用services.AddControllersWithViews(); services.AddControllers(); 服務里面的那個方法來解決問題。


案例三:

未處理的異常。 System.InvalidOperationException:無法找到所需的服務。 請通過在應用程序啟動代碼中對“ConfigureServices(...)”的調用中調用“IServiceCollection.AddRazorPages”來添加所有必需的服務。

當您啟用使用Razor 頁面時會出現此錯誤。 要解決這個問題,需要添加services.AddRazorPages(); 服務。


案例四:

執行請求時發生未處理的異常。

System.InvalidOperationException:沒有注冊類型為“Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]”的服務。

缺少添加身份服務時出現此錯誤。 這可以通過以下方式之一完成:

services.AddDefaultIdentity<IdentityUser>(options =>
{
    //options.Password.RequireDigit = false;
    //options.Password.RequiredLength = 8;
    //options.Password.RequireLowercase = false;
    //options.Password.RequireNonAlphanumeric = false;
    //options.Password.RequireUppercase = false;
}).AddEntityFrameworkStores<ApplicationDbContext>();

要么

services.AddIdentity<IdentityUser, IdentityRole>(options =>
{
    //options.Password.RequireDigit = false;
    //options.Password.RequiredLength = 8;
    //options.Password.RequireLowercase = false;
    //options.Password.RequireNonAlphanumeric = false;
    //options.Password.RequireUppercase = false;
}).AddEntityFrameworkStores<ApplicationDbContext>();

如果您想擴展IdentityUser class 以添加更多屬性,例如LastSignedIn

public class User : IdentityUser
{
    public DateTimeOffset LastSignedIn { get; set; }
}

添加身份服務時,您可以將IdentityUser替換為User

services.AddIdentity<User, IdentityRole>(options => {})
        .AddEntityFrameworkStores<ApplicationDbContext>();

案例五:

未處理的異常。 System.AggregateException:無法構建某些服務(驗證服務描述符時出錯'ServiceType:Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory 1[Microsoft.AspNetCore.Identity.IdentityUser] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.UserClaimsPrincipalFactory 1[Microsoft.AspNetCore.Identity.IdentityUser]':在嘗試激活'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore 6[Microsoft.AspNetCore.Identity.IdentityUser,X.Data.ApplicationDbContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim 1[System.String]、Microsoft.AspNetCore.Identity.IdentityUserLogin 1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken 1[System.String ]]'。)(驗證服務描述符時出錯'ServiceType:Microsoft.AspNetCore.Identity.UserManager 1[Microsoft.AspNetCore.Identity.IdentityUser] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.UserManager 1[Microsoft.AspNetCore.Identity.IdentityUser] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.UserManager 1 [Microsoft.AspNetCore.Identity.IdentityUser]':嘗試激活'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore 6[Microsoft.AspNetCore.Identity.IdentityUser,X.Data.ApplicationDbContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim 1[System.String]、Microsoft.AspNetCore.Identity.IdentityUserLogin 1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken 1[System.String]]'。)(驗證服務描述符“ServiceType:Microsoft.AspNetCore.Identity.ISecurityStampValidator Lifetime:Scoped ImplementationType:Microsoft.AspNetCore.Identity.SecurityStampValidator 1[Microsoft.AspNetCore.Identity.IdentityUser]': Unable to resolve service for type 'X.Data.ApplicationDbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore r,X.Data.ApplicationDbContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim 1[System.String],Microsoft.AspNetCore.Identity.IdentityUserLogin 1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken 1[System.String]]'.) (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity.ITwoFactorSecurityStampValidator Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.TwoFactorSecurityStampValidator 1 [Microsoft.AspNetCore.Identity.IdentityUser]':無法在嘗試激活 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore 6[Microsoft.AspNetCore.Identity.IdentityUser,X.Data.ApplicationDbContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim ] 時解析類型 'X.Data.ApplicationDbContext' 的服務6[Microsoft.AspNetCore.Identity.IdentityUser,X.Data.ApplicationDbContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim 1[System.String],Microsoft.AspNetCore.Identity.IdentityUserLogin 1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken 1[System.String]]'。)(驗證服務描述時出錯 iptor 'ServiceType: Microsoft.AspNetCore.Identity.SignInManager 1[Microsoft.AspNetCore.Identity.IdentityUser] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.SignInManager 1[Microsoft.AspNetCore.Identity.IdentityUser]': 無法解析服務在嘗試激活 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore 6[Microsoft.AspNetCore.Identity.IdentityUser,X.Data.ApplicationDbContext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim 1 時輸入'X.Data.ApplicationDbContext' [System.String]、Microsoft.AspNetCore.Identity.IdentityUserLogin 1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken 1[System.String]]'。)(驗證服務描述符 'ServiceType: Microsoft.AspNetCore 時出錯.Identity.IUserStore 1[Microsoft.AspNetCore.Identity.IdentityUser] Lifetime: Scoped ImplementationType: Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore 6[Microsoft.AspNetCore.Identity.IdentityUser,X.Data.ApplicationDbCo ntext,System.String,Microsoft.AspNetCore.Identity.IdentityUserClaim 1[System.String],Microsoft.AspNetCore.Identity.IdentityUserLogin 1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken 1[System.String]]': Unable to resolve service for type 'X.Data.ApplicationDbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore .Identity.IdentityUserClaim 1[System.String],Microsoft.AspNetCore.Identity.IdentityUserLogin 1[System.String],Microsoft.AspNetCore.Identity.IdentityUserToken`1[System.String]]'。)

當您忘記啟用DbContext服務時會出現此錯誤:

// in this example, we use "Sqlite" to manage connection
services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

如果想使用SQL Server代替Sqlite,可以添加Microsoft.EntityFrameworkCore.SqlServer NPM package:

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

如果在 class 庫項目中定義了ApplicationDbContext class (Namespace: Your_main_project_namespace.Data) ,當你將其引用到主項目時,你需要使用主項目的命名空間名稱調用MigrationsAssembly方法:

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

注意:此 package 的當前版本 (5.0.0) 適用於net5.0 ,因此如果您使用的是netcoreapp3.1 ,則可以改用版本 3.1.10。 不要嘗試升級到最新版本,它會使您的項目崩潰。 如:刪除/替換一些過時的方法/類/接口... IWebHostEnvironment vs IHostingEnvironment ...)


案例六:

值不能是 null。(參數“connectionString”)

此錯誤可能來自文件appsettings.json中的連接字符串名稱:

{
  "ConnectionStrings": {
    "MyConnection": "DataSource=app.db;Cache=Shared"
  }
}

在此示例中,我們將連接字符串命名為MyConnection ,因此當我們嘗試獲取時:

Configuration.GetConnectionString("DefaultConnection")

將拋出異常,因為沒有屬性名稱DefaultConnection


案例七:

這個問題可能來自 append 使用 Finder(在 Mac 上)或資源管理器(在 Windows 上)通過復制粘貼方法投影大量數據文件的方式。 一般情況是:應對wwwroot文件夾:

1個

當 Visual Studio 打開並且某些文件成功復制到wwwroot文件夾(或項目中的其他位置)時,項目將自動保存。 沒有辦法阻止它。

剩余時間將根據以下條件計算:

  • 文件數,
  • 文件大小,
  • 文件類型,
  • 目標文件夾(wwwroot,node_modules ...)
  • 和您的硬件(CPU、RAM、HDD 或 SSD)。

因此,如果要將超過 5000 個圖像或視頻復制到wwwroot文件夾,請小心。 如果出現問題(我什至不知道錯誤來自哪里) ,則無法運行該項目。 在這種情況下,我建議:

  • 等到您的項目完成保存/加載/恢復。 不要采取任何行動試圖阻止或阻止它。
  • 右鍵單擊項目並選擇Edit Project File以編輯.csproj文件。 在這個文件中,如果你發現了這樣的實現:
<ItemGroup>
    <Content Include="wwwroot\">
      <CopyToPublishDirectory>Always</CopyToPublishDirectory>
    </Content>
</ItemGroup>

<ItemGroup>標簽包含<Content>標簽, <Content>標簽提到wwwroot文件夾或從wwwroot文件夾繼承的一些文件夾名稱。 刪除所有這些(包括父標記: <ItemGroup> ),保存文件並等待文件保存/所有包恢復。

  • 清理項目並再次構建/重建。
  • 更多操作:如果您的項目的構建/加載速度變得非常慢,請嘗試右鍵單擊目標文件夾(在本例中為:wwwroot)並選擇Exclude From Project 然后等待 Visual Studio 完成操作,再次右鍵單擊文件夾選擇Include From Project 需要等待操作(排除/包含的時間可能相同)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM