Скриншот исключения
Я поискал в Интернете, чтобы попытаться нашел решение, но ничего не сработало и не применимо к моему случаю.
В нем говорится, что Stream.Length выдал исключение, но, как я нашел в Интернете, люди сказали проверить метод .CanSeek и для каждого открытого потока я проверил, и все они вернули true.
Вот доказательство того, что он считывает длину потока:
Вывод отладки (извините за качество, на скриншотах окно вывода отладки удалялось).И это прямо перед возвратом элемента, в данном случае пользователя, и до него всё работает.
Вот мой код этого метода:< /p>
Код: Выделить всё
public async Task RegisterAsync(RegistrationRequest body)
{
// Create a new instance of the IHttpClientFactory
var httpClient = _httpClientFactory.CreateClient("default");
// Create a MemoryStream to be able to use compression
using (var memoryContentStream = new MemoryStream())
{
await JsonSerializer.SerializeAsync(memoryContentStream, body);
// CAN SEEK returns true
var canSeek = memoryContentStream.CanSeek;
memoryContentStream.Seek(0, SeekOrigin.Begin);
// Use HttpRequestMessage instead of the .PostAsync shortcut but either could be used
using (var httpRequest = new HttpRequestMessage(
HttpMethod.Post,
"/api/Accounts/register"))
{
// Add headers to the call
httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpRequest.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
using (var compressedMemoryContentStream = new MemoryStream())
{
// Compress the content
using (var gzipStream = new GZipStream(
compressedMemoryContentStream, CompressionMode.Compress))
{
memoryContentStream.CopyTo(gzipStream);
gzipStream.Flush();
compressedMemoryContentStream.Position = 0;
// CAN SEEK returns true
var canSeek2 = compressedMemoryContentStream.CanSeek;
// Create a stream
using (var streamContent = new StreamContent(compressedMemoryContentStream))
{
// Add headers to the call
streamContent.Headers.ContentType =
new MediaTypeHeaderValue("application/json");
streamContent.Headers.ContentEncoding.Add("gzip");
httpRequest.Content = streamContent;
var response = await httpClient.SendAsync(
httpRequest,
HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
// THIS IS WHERE IT DOESN'T WORK ANYMORE, even thought .Content shows the length of the stream
var stream = await response.Content.ReadAsStreamAsync();
var user = await JsonSerializer.DeserializeAsync(stream);
return user;
}
}
}
}
}
}
Локальные значения стека
ОБНОВЛЕНИЕ
Вот код, вызывающий метод потока:
Код: Выделить всё
async Task ValidSubmit()
{
try
{
var catId = _configuration["OtherCategory"];
_processing = true;
var newRequest = new RegistrationRequest()
{
FirstName = RegistrationRequest.FirstName,
LastName = RegistrationRequest.LastName,
CategoryId = Guid.Parse(catId),
PhoneNumber = RegistrationRequest.PhoneNumber,
Password = RegistrationRequest.Password
};
// RegistrationRequest.CategoryId = Guid.Parse(this.CategoryId);
IsSuccess = true;
await AuthenticationService.RegisterAsync(newRequest);
// SuccessNotification();
_navigationManager.NavigateTo("code-verification");
}
catch (Exception e)
{
throw;
}
}
"Невозможно получить доступ к закрытому потоку"
Невозможно получить доступ к закрытому потоку p>
at >System.ThrowHelper.ThrowObjectDisposeException_StreamClosed(String
objectName)
at System.IO.MemoryStream.Write(Byte[] буфер, смещение Int32, Int32 count)
в System.IO.Compression.DeflateStream.PurgeBuffers(логическое размещение)
в System.IO.Compression.DeflateStream.Dispose(логическое размещение)
в System.IO.Stream. Close()
в System.IO.Compression.GZipStream.Dispose(логическое размещение)
в System.IO.Stream.Close()
в Website.UI.Services.AuthenticationService.d__2.MoveNext()
в
C:\Users\something\source\repos\Website.Website \Website.UI\Services\AuthenticationService.cs:line
75
at Website.UI.Components.Pages.PageComponents.SignUpComponent.d__8.MoveNext()
в
C:\Users\something\source\repos\Website.Website\Website.UI\Components\Pages\PageComponents \SignUpComponent.razor:line
114
Подробнее здесь: https://stackoverflow.com/questions/792 ... of-type-sy