Skip to content

Scaffolding exceptions for Blazor Web App #2694

Closed

Description

@guardrex

File a bug

Include your code

Steps to reproduce are basic use of the scaffolder without any custom code ...

  1. Create a new BWA with Individual Accounts.
  2. In Solution Explorer, right-click Add > New Scaffolded Item.
  3. Select Identity > Blazor Identity. Select the Add button.
  4. On the Add Blazor Identity step, override the file for Pages\Manage\EnableAuthenticator in the list of pages. Select the app's DBContext class. Select the Add button.

Exception

Include stack traces

Stack Trace:

Finding the generator 'blazor-identity'...
Running the generator 'blazor-identity'...
No database provider found. Using 'SqlServer' by default for new DbContext creation!
Using 'SQL Server' by default!
Empty or invalid namespace provided, using default namespace.
Added Blazor identity file : C:\Users\xxx\Desktop\BWA80IdentityDELETEME\BWA80Identity\BWA80Identity\Components\Account\Pages\Manage\EnableAuthenticator.razor
Modified C:\Users\xxx\Desktop\BWA80IdentityDELETEME\BWA80Identity\BWA80Identity\Program.cs.
Value cannot be null. (Parameter 'path')
   at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.<BuildCommandLine>b__6_0()
   at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
   at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.Execute(String[] args)
   at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)

Result

It seems like the scaffolder is working. The EnableAuthenticator component is present. However, I only ask for the EnableAuthenticator component, but the scaffolder is giving the app all of them ...

image

Anyway ... kill the app and restart it ... here is the next exception during migrations on first run ...

fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
      An error occurred using the connection to database 'aspnet-BWA80Identity-9e2925d7-47fc-4af2-93c4-fb04266c4f5d' on server '(localdb)\mssqllocaldb'.
fail: Microsoft.EntityFrameworkCore.Query[10100]
      An exception occurred while iterating over the results of a query for context type 'BWA80Identity.Data.ApplicationDbContext'.
      System.InvalidOperationException: An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure' to the 'UseSqlServer' call.
       ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot open database "aspnet-BWA80Identity-9e2925d7-47fc-4af2-93c4-fb04266c4f5d" requested by the login. The login failed.
      Login failed for user 'xxx'.
         at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
         at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
         at Microsoft.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
         at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
         at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
         at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
      --- End of stack trace from previous location ---
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
         at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
      ClientConnectionId:cfed530f-488e-47e5-839f-f6628ed1def6
      Error Number:4060,State:1,Class:11
         --- End of inner exception stack trace ---
         at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
      System.InvalidOperationException: An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure' to the 'UseSqlServer' call.
       ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot open database "aspnet-BWA80Identity-9e2925d7-47fc-4af2-93c4-fb04266c4f5d" requested by the login. The login failed.
      Login failed for user 'XXXXXX'.
         at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
         at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
         at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
         at Microsoft.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
         at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
         at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
         at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
         at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
         at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
      --- End of stack trace from previous location ---
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
         at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
      ClientConnectionId:cfed530f-488e-47e5-839f-f6628ed1def6
      Error Number:4060,State:1,Class:11
         --- End of inner exception stack trace ---
         at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
         at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()

I then killed the app and restarted it again ... everything seems to work. I'm able to register a test user, sign them in, and access the authenticator page ...

image

Include provider and version information

Microsoft.VisualStudio.Web.CodeGeneration.Design/Microsoft.DotNet.MSIdentity version: 8.0.2
Target framework: .NET 8.0
Operating system: Windows
IDE: Visual Studio 17.10.0 Preview 1.0

Activity

  1. added
    area-scaffolding
    on Mar 29, 2024
  2. Ksdmg commented on Jun 7, 2024

    @Ksdmg

    I'm facing the same issue.
    Target framework: .NET 8.0
    Operating system: Windows
    IDE: Visual Studio 17.10.1

  3. elbec commented on Jun 18, 2024

    @elbec

    @Ksdmg: Do you found a solution? I have the same issuce in .NET 8.0

  4. constructor commented on Jun 18, 2024

    @constructor

    I ran into this issue today.
    What is the precise cause?
    Anyone got a solution/work around?
    @Ksdmg @elbec

    Using database provider 'Npgsql.EntityFrameworkCore.PostgreSQL'!
    Value cannot be null. (Parameter 'path')
    at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.b__6_0()
    at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
    at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.Execute(String[] args)
    at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)

  5. elbec commented on Jun 19, 2024

    @elbec

    Hello, yes i found yesterday a workaround for me. It did not work for me directly in Visual Stuido. But when i run in project folder with cmd dotnet aspnet-codegenerator identity. Then all files were created without an error!

  6. constructor commented on Jun 19, 2024

    @constructor

    I have a IDesignTimeDbContextFactory, that creates a DbContext. I have checked this by launching a debugger during scaffolding. When the IDesignTimeDbContextFactory returns the DbContext, I still get:

    Using database provider 'Npgsql.EntityFrameworkCore.PostgreSQL'!
    Value cannot be null. (Parameter 'path')
    at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.b__6_0()
    at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
    at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.Execute(String[] args)
    at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)

    Is there any more information on this error? What is the Parameter 'path'?

  7. constructor commented on Jun 19, 2024

    @constructor

    In the very latest VS, with all updates, in my project I have tried:

    1. EF Migrations, and they work perfectly.
    2. RtClick > Add >New Scaffold Item > Razor Pages > Razor Pages using Entity Framwork (CRUD)
      This works perfectly.
    3. RtClick > Add >New Scaffold Item > Razor Component > Razor Components using Entity Framwork (CRUD)
      I get the output:

    Building project ...
    Finding the generator 'blazor'...
    Running the generator 'blazor'...
    Attempting to figure out the EntityFramework metadata for the model and DbContext: 'RadProjectItem'

    Using database provider 'Npgsql.EntityFrameworkCore.PostgreSQL'!

    Value cannot be null. (Parameter 'path')
    at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.b__6_0()
    at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
    at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.Execute(String[] args)
    at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)

    There is no information anywhere to be found.

  8. constructor commented on Jun 21, 2024

    @constructor

    The App.razor file must exist in order for scaffolding to work. I am not using the App.razor file, therefore I removed it. Adding it back into the project makes the scaffolding operation complete without error.

  9. Dennis951 commented on Jun 22, 2024

    @Dennis951

    For me it worked to add back the NavMenu. I looked up what got changed in a new project. Those were these files:

    Screenshot 2024-06-22 030923

  10. guardrex commented on Dec 3, 2024

    @guardrex
    Author

    The App.razor file must exist in order for scaffolding to work.

    That was the case in my situation ... it was there. The good news was just that stopping the app and restarting it resolved the problem, whatever it was ... back in the 8.0 era. I also had the default NavMenu when I hit the errors.

    I just performed the repro steps from my OP ☝ with a .NET 9 BWA (Individual Accounts, global Server rendering). I don't see the errors cropping up. Also, they seem to have fixed the situation where Blazor apps were being offering the option of adding individual Blazor Identity components. I've checked our Blazor guidance on account confirmation/password recovery and scaffolding Identity into a BWA ... it seems fine ... for the moment anyway 😆.

    However, @danroth27, new bugs may have cropped up under 8.0.

    Bug 1: When I scaffolded Identity into my 8.0 test app, it has the wrong connection string name ...

    var connectionString = builder.Configuration.GetConnectionString("BWA80ScaffoldIdentityContextConnection")

    BWA80ScaffoldIdentityContextConnection doesn't match BWA80ScaffoldIdentityContext in the app settings file ...

    "BWA80ScaffoldIdentityContext": "..."

    Bug 2: Even worse: Running the app and going to the Register page puts the app in a WebSocket connection 💀 death spiral 💀, where the page just rapidly keeps reloading (flashing) the UI of the Register page.

    The scaffolding of the connection string probably means that I should close this and open a new issue here on that.

    For the WebSockets connection issue, I don't see an issue on our repo. Do you want to verify that I'm correct on it before I try to open an issue on it? The setup is ...

    • 8.0 BWA
    • Global Server rendering
    • Scaffold Identity into the app (new db context, new db user)
    • Fix the connection string in Program.cs (remove the word "Connection")
    • Run the app and navigate to the Register page
  11. danroth27 commented on Dec 3, 2024

    @danroth27
    Member

    @guardrex The repro steps for this issue don't make sense to me: You start with a Blazor Web App that has Individual User Accounts enabled. Why would you then run the Blazor Identity scaffolder? The Blazor Identity code is already there when you created the project from the template, right?

  12. guardrex commented on Dec 3, 2024

    @guardrex
    Author

    You are correct. I wonder if this went back to some period during 8.0 preview where I wasn't getting Identity components, which would explain why I was trying to scaffold to get the EnableAuthenticator page (or component) in the app. I see now that Identity components are present, and there's no problem with the connection string unless one tries to add Blazor Identity, which isn't supported.

    I'll close this now.

  13. guardrex commented on Dec 3, 2024

    @guardrex
    Author

    @danroth27 ... I think I recall where I went wrong here. I believe this was scaffolding into a BWA without Identity.

    The repro steps are ...

    • 9.0 BWA (NOT adding Identity when the app is created)
    • Global Server rendering
    • Scaffold Identity into the app (new db context, new db user)

    First ...

    builder.Configuration.GetConnectionString("BWA90ForScaffoldingContextConnection")

    ... doesn't match ...

    "ConnectionStrings": {
      "BWA90ForScaffoldingContext": "..."
    }
    • Fix that by removing "Connection"
    • Run the app and go to the Register page.

    💥 ... It gets into a WebSocket loop of some sort reloading the page over and over in rapid succession. It states this over and over in the log ...

    [2024-12-03T19:47:16.070Z] Information: Normalizing '_blazor' to 'https://localhost:7086/_blazor'.
    [2024-12-03T19:47:16.073Z] Information: WebSocket connected to wss://localhost:7086/_blazor?id=cn5kj7sna7Hg-_67KieshA.
    

    ... with a different id on each one.

    If those are reproducible, then I guess ...

    • Close this issue.
    • Open a new issue on this repo for the connection string name problem.
    • Open a new issue on our repo for the WebSocket issue.
  14. added theissue type on Aug 7, 2026
  15. danroth27 commented on Aug 9, 2026

    @danroth27
    Member

    I retested the revised repro in the current Visual Studio experience using a .NET 9 Blazor Web App with no authentication, global Interactive Server rendering, and a new BWA90ForScaffoldingContext.

    The original behavior has changed:

    • Visual Studio no longer offers individual Blazor Identity component selection; scaffolding is all-or-nothing.
    • The original Value cannot be null. (Parameter 'path') exception no longer occurs.
    • The Account files are placed correctly under Components\Account.
    • The Identity packages, ApplicationUser, DbContext, and matching BWA90ForScaffoldingContext connection string are added.
    • The resulting project builds successfully with no warnings or errors.

    However, scaffolding silently leaves the application host integration incomplete:

    • Program.cs is unchanged: no authentication/Identity services, DbContext registration, IdentityRedirectManager, authentication-state provider, email sender, migrations endpoint, or MapAdditionalIdentityEndpoints().
    • App.razor remains globally interactive instead of conditionally disabling interactivity for Identity pages.
    • Routes.razor remains a plain RouteView instead of using AuthorizeRouteView and RedirectToLogin.
    • NavMenu.razor receives no Register/Login/Manage/Logout UI.

    As a result, browsing directly to /Account/Register throws because IdentityRedirectManager is not registered. This is a current, user-visible failure despite the scaffolder reporting success and the project compiling.

    For comparison, dotnet scaffold 20.0.0 now generates a matching connection-string name, so that specific reopened complaint is fixed. In the same project shape it currently places the Account UI beneath an extra project-name directory and fails to build, which is the separate defect tracked by #3716.

    Keeping this issue open for the current Visual Studio failure to apply the required Identity host wiring.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-blazorarea-scaffoldingcustomer-reported

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions