Blazor Server Side выдает исключение при доступе к базе данных через EF Core 3.0 - PullRequest
0 голосов
/ 26 сентября 2019

У меня есть приложение на стороне сервера Blazor, которое использует тот же код, что и мое приложение Razor Pages для входа в систему.На последующем все работает без проблем.Но когда я вызываю код из приложения Blazor, я получаю следующее исключение:

Microsoft.EntityFrameworkCore.Query: Error: An exception occurred while iterating over the results of a query for context type 'ApplySupportTool.Persistence.SupportToolContext'.
System.InvalidOperationException: Invalid attempt to call ReadAsync when reader is closed.
   at Microsoft.Data.Common.ADP.ExceptionWithStackTrace(Exception e)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.AsyncQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()

System.InvalidOperationException: Invalid attempt to call ReadAsync when reader is closed.
   at Microsoft.Data.Common.ADP.ExceptionWithStackTrace(Exception e)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.AsyncQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
Application Insights Telemetry: {"name":"Microsoft.ApplicationInsights.Dev.a4bc939a6fe043bab4c30bf0072682ec.Exception","time":"2019-09-26T06:57:07.6196789Z","iKey":"a4bc939a-6fe0-43ba-b4c3-0bf0072682ec","tags":{"ai.application.ver":"1.0.0.0","ai.cloud.roleInstance":"w00jda","ai.operation.id":"34f69748c45cf34e8c6e05c45cfe51a1","ai.operation.parentId":"|34f69748c45cf34e8c6e05c45cfe51a1.01f80e1228d2214d.","ai.internal.sdkVersion":"il:2.11.0-21511","ai.internal.nodeName":"w00jda.pnet.ch"},"data":{"baseType":"ExceptionData","baseData":{"ver":2,"exceptions":[{"id":28067354,"outerId":0,"typeName":"System.InvalidOperationException","message":"Invalid attempt to call ReadAsync when reader is closed.","hasFullStack":true,"parsedStack":[{"level":0,"method":"Microsoft.Data.Common.ADP.ExceptionWithStackTrace","assembly":"Microsoft.Data.SqlClient, Version=1.0.19249.1, Culture=neutral, PublicKeyToken=23ec7fc2d6eaa4a5","line":0},{"level":1,"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e","line":0},{"level":2,"method":"System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e","line":0},{"level":3,"method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e","line":0},{"level":4,"method":"System.Runtime.CompilerServices.TaskAwaiter`1.GetResult","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e","line":0},{"level":5,"method":"Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor+AsyncQueryingEnumerable`1+AsyncEnumerator+<MoveNextAsync>d__17.MoveNext","assembly":"Microsoft.EntityFrameworkCore.Relational, Version=3.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60","line":0}]}],"severityLevel":"Error","properties":{"AspNetCoreEnvironment":"Development","FormattedMessage":"An exception occurred while iterating over the results of a query for context type 'ApplySupportTool.Persistence.SupportToolContext'.\r\nSystem.InvalidOperationException: Invalid attempt to call ReadAsync when reader is closed.\r\n   at Microsoft.Data.Common.ADP.ExceptionWithStackTrace(Exception e)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.AsyncQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()","RequestId":"80000021-0003-ff00-b63f-84710c7967bb","ParentId":"0000000000000000","TransportConnectionId":"xUPNQItb15c1ROVvacG0xw","contextType":"ApplySupportTool.Persistence.SupportToolContext","error":"System.InvalidOperationException: Invalid attempt to call ReadAsync when reader is closed.\r\n   at Microsoft.Data.Common.ADP.ExceptionWithStackTrace(Exception e)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.AsyncQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()","RequestPath":"/_blazor","CategoryName":"Microsoft.EntityFrameworkCore.Query","SpanId":"01f80e1228d2214d","{OriginalFormat}":"An exception occurred while iterating over the results of a query for context type '{contextType}'.{newline}{error}","EventId":"10100","EventName":"Microsoft.EntityFrameworkCore.Query.QueryIterationFailed","TraceId":"34f69748c45cf34e8c6e05c45cfe51a1","DeveloperMode":"true"}}}}
Exception thrown: 'System.InvalidOperationException' in System.Private.CoreLib.dll
Exception thrown: 'System.InvalidOperationException' in System.Private.CoreLib.dll
Exception thrown: 'System.InvalidOperationException' in System.Private.CoreLib.dll

Моя страница Blazor:

<div class="text-center">
        <form method="post" class="form-signin shadow bg-white rounded">
            <img class="mb-4" src="images/apply_solutions_logo.png" alt="" width="200">

            <label class="sr-only"></label>
            <input placeholder="@LocalizedStrings.UsernameLabel" class="form-control" @bind="Username" />
            <label class="sr-only"></label>
            <input type="password" placeholder="@LocalizedStrings.PasswordLabel" class="form-control" @bind="Password" />

            <div class="mt-3">
                <label asp-for="LoginUserQuery.RememberMe">
                    <input type="checkbox" id="rememberMeCheckBox" class="form-check-input" @bind="RememberMe" />
                    <label class="form-check-label" for="rememberMeCheckBox" >@LocalizedStrings.RememberMeLabel</label>
                </label>
            </div>
            <button type="submit" class="btn btn-primary btn-block" onclick="@SignInAsync()">@LocalizedStrings.LoginLabel</button>
            <div asp-validation-summary="All" class="text-danger"></div>
            <div class="@NavMenuCssClass">Fooo</div>
        </form>
    </div>

    @code {

        public string Username { get; set; }
        public string Password { get; set; }
        public bool RememberMe { get; set; }

        bool isInvalidLoginAttempt;

        string NavMenuCssClass => isInvalidLoginAttempt ? null : "collapse";

        async Task SignInAsync()
        {
            var result = await Mediator.Send(new LoginUserQuery{Username = Username, Password = Password, RememberMe = RememberMe});

            if (result.Succeeded)
            {
                NavigationManager.NavigateTo("/");
            }
            else if (result.IsLockedOut)
            {
                NavigationManager.NavigateTo("/Lockout");
            }
            else
            {
                isInvalidLoginAttempt = true;
            }
        }
    }

И запрос следующий:

        public async Task<SignInResult> Handle(LoginUserQuery request, CancellationToken cancellationToken)
        {
            var result = await signInManager.PasswordSignInAsync(request.Username, request.Password, request.RememberMe);

            if (result.Succeeded) {
                ApplicationUser user = await userManager.GetUserAsync(request.Username);
                user.SetLastLogin();
                await userManager.UpdateAsync(user);
            }

            return result;
        }

Нужно ли выполнять асинхронные вызовы по-другому?

...