dodyg/practical-aspnetcore

exception when viewing pages of security\authentication-with-identity sample

Closed this issue · 25 comments

I'm using .net 5.0.102 and when viewing pages got following exceptions.
Did I miss something? but the readme doesn't say any special configurations.

PS C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src> dotnet watch run
watch : Started
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
User profile is available. Using 'C:\Users\YANG.LEI\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[58]
Creating key {b5316108-ee28-43bf-9b66-38dcacb137c3} with creation date 2021-02-22 04:41:34Z, activation date 2021-02-22 04:41:34Z, and expiration date 2021-05-23 04:41:34Z.
info: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[39]
Writing data to file 'C:\Users\YANG.LEI\AppData\Local\ASP.NET\DataProtection-Keys\key-b5316108-ee28-43bf-9b66-38dcacb137c3.xml'.
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:5000/favicon.ico
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 66.6737ms 404
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:5000/
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
Executing endpoint 'WebApplication.Controllers.HomeController.Index (authentication-with-identity)'
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Route matched with {action = "Index", controller = "Home"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Index() on controller WebApplication.Controllers.HomeController (authentication-with-identity).
info: Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor[1]
Executing ViewResult, running view Index.
info: Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor[4]
Executed ViewResult - view Index executed in 394.2386ms.
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Executed action WebApplication.Controllers.HomeController.Index (authentication-with-identity) in 428.9772ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint 'WebApplication.Controllers.HomeController.Index (authentication-with-identity)'
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 528.622ms 200 text/html; charset=utf-8
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:5000/
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
Executing endpoint 'WebApplication.Controllers.HomeController.Index (authentication-with-identity)'
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
Route matched with {action = "Index", controller = "Home"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Index() on controller WebApplication.Controllers.HomeController (authentication-with-identity).
info: Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor[1]
Executing ViewResult, running view Index.
info: Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor[4]
Executed ViewResult - view Index executed in 23.8567ms.
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
Executed action WebApplication.Controllers.HomeController.Index (authentication-with-identity) in 24.7353ms
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[1]
Executed endpoint 'WebApplication.Controllers.HomeController.Index (authentication-with-identity)'
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 29.9904ms 200 text/html; charset=utf-8
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:5000/Account/Register
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: Endpoint WebApplication.Controllers.AccountController.Register (authentication-with-identity) contains authorization metadata, but a middleware was not found that supports authorization.
Configure your application startup by adding app.UseAuthorization() inside the call to Configure(..) in the application startup code. The call to app.UseAuthorization() must appear between app.UseRouting() and app.UseEndpoints(...).
at Microsoft.AspNetCore.Routing.EndpointMiddleware.ThrowMissingAuthMiddlewareException(Endpoint endpoint)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 131.074ms 500 text/html; charset=utf-8
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:5000/Account/Login
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: Endpoint WebApplication.Controllers.AccountController.Login (authentication-with-identity) contains authorization metadata, but a middleware was not found that supports authorization.
Configure your application startup by adding app.UseAuthorization() inside the call to Configure(..) in the application startup code. The call to app.UseAuthorization() must appear between app.UseRouting() and app.UseEndpoints(...).
at Microsoft.AspNetCore.Routing.EndpointMiddleware.ThrowMissingAuthMiddlewareException(Endpoint endpoint)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 35.5669ms 500 text/html; charset=utf-8
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://localhost:5000/RestrictedArea
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: Endpoint WebApplication.Controllers.RestrictedAreaController.Index (authentication-with-identity) contains authorization metadata, but a middleware was not found that supports authorization.
Configure your application startup by adding app.UseAuthorization() inside the call to Configure(..) in the application startup code. The call to app.UseAuthorization() must appear between app.UseRouting() and app.UseEndpoints(...).
at Microsoft.AspNetCore.Routing.EndpointMiddleware.ThrowMissingAuthMiddlewareException(Endpoint endpoint)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished in 25.5265ms 500 text/html; charset=utf-8

dodyg commented

Oh bummer. Let me check it tonight when I have access to my computer. Thanks for the report.

dodyg commented

Didn't get a chance last night. Will try today.

thanks!

dodyg commented

It's fixed. Just download the latest version.

You can see the fixes in these two commits

3690b37
f0368e6

Thanks for filling an bug report.

Sorry for late response but i still fail to run this sample( different error this time). Before creating a new issue, i'd like to post the issue here and see if there's any feed back.

Steps:

  1. clone latest repo, branch net5.0
  2. go to projects\security\authentication-with-identity, run build.bat
  3. run authentication-with-identity.exe

Exceptions:

PS C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src\bin\Debug\net5.0> .\authentication-with-identity.exe
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[63]
User profile is available. Using 'C:\Users\LeiYang\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
crit: Microsoft.AspNetCore.Hosting.Diagnostics[6]
Application startup exception
System.InvalidOperationException: Cannot resolve scoped service 'WebApplication.Data.ApplicationDbContext' from root provider.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.Microsoft.Extensions.DependencyInjection.ServiceLookup.IServiceProviderEngineCallback.OnResolve(Type serviceType, IServiceScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
at WebApplication.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env) in C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src\Program.cs:line 80
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.b__0(IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass15_0.b__1(IApplicationBuilder app)
at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
Unhandled exception. System.InvalidOperationException: Cannot resolve scoped service 'WebApplication.Data.ApplicationDbContext' from root provider.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.Microsoft.Extensions.DependencyInjection.ServiceLookup.IServiceProviderEngineCallback.OnResolve(Type serviceType, IServiceScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
at WebApplication.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env) in C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src\Program.cs:line 80
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.b__0(IApplicationBuilder builder)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass15_0.b__1(IApplicationBuilder app)
at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
at WebApplication.Program.Main(String[] args) in C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src\Program.cs:line 16
PS C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src\bin\Debug\net5.0>

dodyg commented

I will review this today.

maybe it was due to lack of some database in my environment?
but if the readme contains steps to setup(such as where to specify connection strings, and whether some initialize sql is needed) then it will be great.

dodyg commented
dodyg commented

@LeiYangGH please follow these two steps

steps

This is full log:

PS C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src> git status
On branch net5.0
Your branch is up to date with 'origin/net5.0'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   ../../../../global.json

no changes added to commit (use "git add" and/or "git commit -a")
PS C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src> git diff
diff --git a/global.json b/global.json
index 355d35dd..314118e7 100644
--- a/global.json
+++ b/global.json
@@ -1,6 +1,6 @@
 {
   "sdk": {
-    "version": "5.0.100",
+    "version": "5.0.203",
     "rollForward": "latestPatch"
   }
 }
\ No newline at end of file
PS C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src> dotnet build

欢迎使用 .NET 5.0!
---------------------
SDK 版本: 5.0.203

遥测
---------
.NET 工具会收集用法数据,帮助我们改善你的体验。它由 Microsoft 收集并与社区共享。你可通过使用喜欢的 shell 将 DOTNET_CLI_TELEMETRY_OPTOUT 环境变量设置为 "1""true" 来选择退出遥测。

阅读有关 .NET CLI 工具遥测的更多信息: https://aka.ms/dotnet-cli-telemetry

----------------
已安装 ASP.NET Core HTTPS 开发证书。
若要信任该证书,请运行 "dotnet dev-certs https --trust" (仅限 Windows 和 macOS)。
了解 HTTPS: https://aka.ms/dotnet-https
----------------
编写你的第一个应用: https://aka.ms/dotnet-hello-world
查找新增功能: https://aka.ms/dotnet-whats-new
浏览文档: https://aka.ms/dotnet-docs
在 GitHub 上报告问题和查找源: https://github.com/dotnet/core
使用 "dotnet --help" 查看可用命令或访问: https://aka.ms/dotnet-cli
--------------------------------------------------------------------------------------
用于 .NET 的 Microsoft (R) 生成引擎版本 16.9.0+57a23d249
版权所有(C) Microsoft Corporation。保留所有权利。

  正在确定要还原的项目…
  已还原 C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src\authentication-with-identity.csproj (用时 14.37 sec)。
  authentication-with-identity -> C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src\bin\Debug\net5.0\authentication-with-identity.dll
  authentication-with-identity -> C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src\bin\Debug\net5.0\authentication-with-identity.Views.dll

已成功生成。
    0 个警告
    0 个错误

已用时间 00:00:23.88
PS C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src> dotnet run
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[63]
      User profile is available. Using 'C:\Users\YANG.LEI\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
crit: Microsoft.AspNetCore.Hosting.Diagnostics[6]
      Application startup exception
      System.InvalidOperationException: Cannot resolve scoped service 'WebApplication.Data.ApplicationDbContext' from root provider.
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)
         at Microsoft.Extensions.DependencyInjection.ServiceProvider.Microsoft.Extensions.DependencyInjection.ServiceLookup.IServiceProviderEngineCallback.OnResolve(Type serviceType, IServiceScope scope)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
         at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
         at WebApplication.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env) in C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src\Program.cs:line 80
         at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
         at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
         at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
         at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
         at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass15_0.<UseStartup>b__1(IApplicationBuilder app)
         at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
         at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
         at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
Unhandled exception. System.InvalidOperationException: Cannot resolve scoped service 'WebApplication.Data.ApplicationDbContext' from root provider.
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.Microsoft.Extensions.DependencyInjection.ServiceLookup.IServiceProviderEngineCallback.OnResolve(Type serviceType, IServiceScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
   at WebApplication.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env) in C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src\Program.cs:line 80
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass15_0.<UseStartup>b__1(IApplicationBuilder app)
   at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
   at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
   at WebApplication.Program.Main(String[] args) in C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src\Program.cs:line 16
PS C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src>


dodyg commented

Cannot resolve scoped service 'WebApplication.Data.ApplicationDbContext'

This is weird

services.AddDbContext<ApplicationDbContext>(options=>

The code is right there.

Can you try changing the UseSqlite

=> options.UseSqlite(@"Data Source=C:\identity.db");

Changed to this:

			services.AddDbContext<ApplicationDbContext>(options=>
				options.UseSqlite("Data Source=C:\\identity.db"));

But error is the same.

PS C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src> dotnet build
用于 .NET 的 Microsoft (R) 生成引擎版本 16.8.3+39993bd9d
版权所有(C) Microsoft Corporation。保留所有权利。

  正在确定要还原的项目…
  所有项目均是最新的,无法还原。
  authentication-with-identity -> C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src\bin\Debug\net5.0\authentication-with-identity.dll
  authentication-with-identity -> C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src\bin\Debug\net5.0\authentication-with-identity.Views.dll

已成功生成。
    0 个警告
    0 个错误

已用时间 00:00:02.43
PS C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src> dotnet run
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[63]
      User profile is available. Using 'C:\Users\LeiYang\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
crit: Microsoft.AspNetCore.Hosting.Diagnostics[6]
      Application startup exception
      System.InvalidOperationException: Cannot resolve scoped service 'WebApplication.Data.ApplicationDbContext' from root provider.
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)
         at Microsoft.Extensions.DependencyInjection.ServiceProvider.Microsoft.Extensions.DependencyInjection.ServiceLookup.IServiceProviderEngineCallback.OnResolve(Type serviceType, IServiceScope scope)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
         at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
         at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
         at WebApplication.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env) in C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src\Program.cs:line 81
         at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
         at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
         at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
         at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
         at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass15_0.<UseStartup>b__1(IApplicationBuilder app)
         at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
         at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
         at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
Unhandled exception. System.InvalidOperationException: Cannot resolve scoped service 'WebApplication.Data.ApplicationDbContext' from root provider.
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.Microsoft.Extensions.DependencyInjection.ServiceLookup.IServiceProviderEngineCallback.OnResolve(Type serviceType, IServiceScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
   at WebApplication.Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env) in C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src\Program.cs:line 81
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.Invoke(Object instance, IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.ConfigureBuilder.<>c__DisplayClass4_0.<Build>b__0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass15_0.<UseStartup>b__1(IApplicationBuilder app)
   at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
   at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
   at WebApplication.Program.Main(String[] args) in C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src\Program.cs:line 16
PS C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src> git diff
diff --git a/projects/security/authentication-with-identity/src/Program.cs b/projects/security/authentication-with-identity/src/Program.cs
index 31f79413..0e2a1888 100644
--- a/projects/security/authentication-with-identity/src/Program.cs
+++ b/projects/security/authentication-with-identity/src/Program.cs
@@ -32,7 +32,7 @@ namespace WebApplication
         {
                        // Add the database context we will use.
                        services.AddDbContext<ApplicationDbContext>(options=>
-                               options.UseSqlite("Data Source=identity_db.db"));
+                               options.UseSqlite("Data Source=C:\\identity.db"));

                        // Add Identity and configure it to use the default user and role models and the database context we just added.
                        services.AddIdentity<IdentityUser, IdentityRole>()
@@ -72,6 +72,7 @@ namespace WebApplication

                        app.UseAuthentication();
             app.UseAuthorization();
+            //app.UseDefaultServiceProvider(options => { options.ValidateScopes = false; });
             app.UseEndpoints(endpoints =>
             {
                 endpoints.MapDefaultControllerRoute();
PS C:\G\practical-aspnetcore\projects\security\authentication-with-identity\src>
dodyg commented

@lohithgn What do you think is the problem here? We need a third pair of eyes

@dodyg will take a look at it and will update

@dodyg I have no issue running the sample. I tried the following two ways of running the app:

  1. Navigate to projects/security/authentication-with-identity/src. then dotnet build. then dotnet run. Was able to register a user, login and logout
  2. Navigate to projects/security/. Execute build.bat. Navigate to projects/security/authentication-with-identity/src/bin/debug/net5.0. Execute exe authentication-with-identity.exe. I was able to register a user, login and logout.

The logs are not providing any other information. so that's tricky to iron this out.

having said that - i tried above steps from command line.

I just opened the project in Visual Studio and i put a breakpoint in line 81 in program.cs. I see the exception.

image

interesting ...

@dodyg @LeiYangGH can you try the following code for Configure()

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ApplicationDbContext dbContext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

			app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });

            using (var client = dbContext)
            {
                client.Database.EnsureCreated();
            }
        }

It's recommended to set up the database in Main and to directly create the DI scope required.
https://docs.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/sql?view=aspnetcore-5.0&tabs=visual-studio#add-the-seed-initializer

@Tratcher that is true.

@dodyg may be you can update the sample. Dont do the DB initialize check in Configure() instead do it in Main.

@lohithgn I CAN run the sample if update code like you wrote above. Thanks!

Configure(IApplicationBuilder app, IWebHostEnvironment env, ApplicationDbContext context)
...

@LeiYangGH we are working on a better solution than what i proposed. i am in the middle of creating a PR. I suggest you wait for the PR to be merged.

@LeiYangGH here is the PR which is the correct way of doing the DB creation - #291

dodyg commented

Excellent - thanks everyone. I never use EF Core so I have no idea about this subtleties in behavior.

Startup is a magic. You need to know when the Configure() and ConfigureServices() are called in the lifecycle :). This was not EF thing - rather - what is the right place to ensure database is created. Happy to help anytime :)

dodyg commented

You need to know when the Configure() and ConfigureServices() are called in the lifecycle :).

This can be a new sample