繁体   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