C# 未终止的字符串。需要将字节[]转换为Json的分隔符

C# 未终止的字符串。需要将字节[]转换为Json的分隔符,c#,arrays,json,api,xamarin,C#,Arrays,Json,Api,Xamarin,我的应用程序出现了一个尴尬的错误,我想不出原因。。。 完整的堆栈跟踪如下所示: FALHA NO POST: ProcedimentosMidias :Unterminated string. Expected delimiter: ". Path '[12].ImageBytes', line 1, position 17190742. - em Newtonsoft.Json.JsonTextReader.ReadStringIntoBuffer(Char quote) em N

我的应用程序出现了一个尴尬的错误,我想不出原因。。。 完整的堆栈跟踪如下所示:

FALHA NO POST: ProcedimentosMidias :Unterminated string. Expected delimiter: ". Path '[12].ImageBytes', line 1, position 17190742. - em Newtonsoft.Json.JsonTextReader.ReadStringIntoBuffer(Char quote)

em Newtonsoft.Json.JsonTextReader.ReadAsBytes()

em Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)

em Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)

em Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)

em Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateList(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, String id)

em Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, Object existingValue, String id)

em Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)

em Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)

em Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)

em Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)

em App_Services_ProcedimentosMidias.App_Services_ProcedimentosMidias_Load(Object sender, EventArgs e) na C:xxxxx.xxxxx.com.brapp_servicesProcedimentosMidias.aspx.vb:linha 48

该场景是,移动应用程序(Xamarin/C#)传输一些图像/文件,将它们序列化为字节[],然后放入转换为JSON并通过HTTP传输的模型中

然后,将接收到的字节[]反序列化回image/file。 移动应用程序中的序列化代码如下:

public static byte[] GetFileAsByteArray(string filePath)
        {
            if (System.IO.File.Exists(filePath))
            {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                int bufferSize = 1024 * 1024;
                FileInputStream fis = new FileInputStream(new File(filePath));
                byte[] buffer = new byte[bufferSize];
                int read = 0;

                while((read = fis.Read(buffer)) > 0)
                {
                    bos.Write(buffer, 0, read);
                }

                fis.Close();
                return bos.ToByteArray();
            }
            else
            {
                return new byte[0];
            }

            //return System.IO.File.ReadAllBytes(filePath);

        }
  • 我将此方法中的字节[]放在模型上的ImageByte[]变量上,该变量使用Newtonsoft.Json包转换为Json,并通过HTTP POST和Refit传输
同一个用户,也得到了这个错误,我猜是相关的

POST ProcedimentosMidias retornou um erro: Data.ExceptionSystem.AggregateException: One or more errors occurred. (Error while copying content to a stream.) -> System.Net.Http.HttpRequestException: Error while copying content to a stream. -> System.IO.IOException: Unable to read data from the transport connection: Connection reset by peer. -> System.Net.Sockets.SocketException: Connection reset by peer - End of inner exception stack trace - at System.Net.Sockets.Socket+AwaitableSocketAsyncEventArgs.ThrowException (System.Net.Sockets.SocketError error) [0x00007] in <94ee25288e5b447880f446c994feac0b>:0 at System.Net.Sockets.Socket+AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult (System.Int16 token) [0x0001f] in <94ee25288e5b447880f446c994feac0b>:0 at System.Threading.Tasks.ValueTask+ValueTaskSourceAsTask+<>c.<.cctor>b__4_0 (System.Object state) [0x00030] in <210883430b4a425fbc7186ded653500e>:0 - End of stack trace from previous location where exception was thrown - at Mono.Net.Security.MobileAuthenticatedStream.InnerWrite (System.Boolean sync, System.Threading.CancellationToken cancellationToken) [0x000d3] in <94ee25288e5b447880f446c994feac0b>:0 at Mono.Net.Security.AsyncProtocolRequest.ProcessOperation (System.Threading.CancellationToken cancellationToken) [0x00199] in <94ee25288e5b447880f446c994feac0b>:0 at Mono.Net.Security.AsyncProtocolRequest.StartOperation (System.Threading.CancellationToken cancellationToken) [0x0008b] in <94ee25288e5b447880f446c994feac0b>:0 at Mono.Net.Security.MobileAuthenticatedStream.StartOperation (Mono.Net.Security.MobileAuthenticatedStream+OperationType type, Mono.Net.Security.AsyncProtocolRequest asyncRequest, System.Threading.CancellationToken cancellationToken) [0x0024b] in <94ee25288e5b447880f446c994feac0b>:0 at System.Net.Http.HttpConnection.WriteAsync (System.ReadOnlyMemory`1[T] source) [0x0015d] in <150dffdc6e124595ac779aab932eba71>:0 at System.Net.Http.HttpContent.CopyToAsyncCore (System.Threading.Tasks.ValueTask copyTask) [0x00067] in <150dffdc6e124595ac779aab932eba71>:0 - End of inner exception stack trace - at System.Net.Http.HttpContent.CopyToAsyncCore (System.Threading.Tasks.ValueTask copyTask) [0x0008f] in <150dffdc6e124595ac779aab932eba71>:0 at System.Net.Http.HttpConnection.SendRequestContentAsync (System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpConnection+HttpContentWriteStream stream, System.Threading.CancellationToken cancellationToken) [0x000a0] in <150dffdc6e124595ac779aab932eba71>:0 at System.Net.Http.HttpConnection.SendAsyncCore (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x012e6] in <150dffdc6e124595ac779aab932eba71>:0 at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync (System.Net.Http.HttpConnection connection, System.Net.Http.HttpRequestMessage request, System.Boolean doRequestAuth, System.Threading.CancellationToken cancellationToken) [0x0012b] in <150dffdc6e124595ac779aab932eba71>:0 at System.Net.Http.HttpConnectionPool.SendWithRetryAsync (System.Net.Http.HttpRequestMessage request, System.Boolean doRequestAuth, System.Threading.CancellationToken cancellationToken) [0x0014b] in <150dffdc6e124595ac779aab932eba71>:0 at System.Net.Http.RedirectHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x000ba] in <150dffdc6e124595ac779aab932eba71>:0 at System.Net.Http.HttpClient.FinishSendAsyncBuffered (System.Threading.Tasks.Task`1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean disposeCts) [0x0017e] in <150dffdc6e124595ac779aab932eba71>:0 at Refit.RequestBuilderImplementation+<>c__DisplayClass23_0.b__0 (System.Net.Http.HttpClient client, System.Object[] paramList) [0x00173] in :0 - End of inner exception stack trace - -> (Inner Exception #0) System.Net.Http.HttpRequestException: Error while copying content to a stream. -> System.IO.IOException: Unable to read data from the transport connection: Connection reset by peer. -> System.Net.Sockets.SocketException: Connection reset by peer - End of inner exception stack trace - at System.Net.Sockets.Socket+AwaitableSocketAsyncEventArgs.ThrowException (System.Net.Sockets.SocketError error) [0x00007] in <94ee25288e5b447880f446c994feac0b>:0 at System.Net.Sockets.Socket+AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult (System.Int16 token) [0x0001f] in <94ee25288e5b447880f446c994feac0b>:0 at System.Threading.Tasks.ValueTask+ValueTaskSourceAsTask+<>c.<.cctor>b__4_0 (System.Object state) [0x00030] in <210883430b4a425fbc7186ded653500e>:0 - End of stack trace from previous location where exception was thrown - at Mono.Net.Security.MobileAuthenticatedStream.InnerWrite (System.Boolean sync, System.Threading.CancellationToken cancellationToken) [0x000d3] in <94ee25288e5b447880f446c994feac0b>:0 at Mono.Net.Security.AsyncProtocolRequest.ProcessOperation (System.Threading.CancellationToken cancellationToken) [0x00199] in <94ee25288e5b447880f446c994feac0b>:0 at Mono.Net.Security.AsyncProtocolRequest.StartOperation (System.Threading.CancellationToken cancellationToken) [0x0008b] in <94ee25288e5b447880f446c994feac0b>:0 at Mono.Net.Security.MobileAuthenticatedStream.StartOperation (Mono.Net.Security.MobileAuthenticatedStream+OperationType type, Mono.Net.Security.AsyncProtocolRequest asyncRequest, System.Threading.CancellationToken cancellationToken) [0x0024b] in <94ee25288e5b447880f446c994feac0b>:0 at System.Net.Http.HttpConnection.WriteAsync (System.ReadOnlyMemory`1[T] source) [0x0015d] in <150dffdc6e124595ac779aab932eba71>:0 at System.Net.Http.HttpContent.CopyToAsyncCore (System.Threading.Tasks.ValueTask copyTask) [0x00067] in <150dffdc6e124595ac779aab932eba71>:0 - End of inner exception stack trace - at System.Net.Http.HttpContent.CopyToAsyncCore (System.Threading.Tasks.ValueTask copyTask) [0x0008f] in <150dffdc6e124595ac779aab932eba71>:0 at System.Net.Http.HttpConnection.SendRequestContentAsync (System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpConnection+HttpContentWriteStream stream, System.Threading.CancellationToken cancellationToken) [0x000a0] in <150dffdc6e124595ac779aab932eba71>:0 at System.Net.Http.HttpConnection.SendAsyncCore (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x012e6] in <150dffdc6e124595ac779aab932eba71>:0 at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync (System.Net.Http.HttpConnection connection, System.Net.Http.HttpRequestMessage request, System.Boolean doRequestAuth, System.Threading.CancellationToken cancellationToken) [0x0012b] in <150dffdc6e124595ac779aab932eba71>:0 at System.Net.Http.HttpConnectionPool.SendWithRetryAsync (System.Net.Http.HttpRequestMessage request, System.Boolean doRequestAuth, System.Threading.CancellationToken cancellationToken) [0x0014b] in <150dffdc6e124595ac779aab932eba71>:0 at System.Net.Http.RedirectHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x000ba] in <150dffdc6e124595ac779aab932eba71>:0 at System.Net.Http.HttpClient.FinishSendAsyncBuffered (System.Threading.Tasks.Task`1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean disposeCts) [0x0017e] in <150dffdc6e124595ac779aab932eba71>:0 at Refit.RequestBuilderImplementation+<>c__DisplayClass23_0.b__0 (System.Net.Http.HttpClient client, System.Object[] paramList) [0x00173] in :0 <-
你们能帮我弄清楚吗?
多谢各位

错误消息显示
未终止字符串。预期的分隔符:“
我想你需要做的就是:string json=Encoding.UTF8.GetString(bytes);我忘了提到,只有2到3个用户有这个问题……所有其他用户都上传的很好……如果是UTF8问题,这不会发生在每个人身上吗?我添加了服务器端代码来转换byte[]如图所示,由于我看到问题可能出在服务器端转换上……现在我不知道应用程序是否正在上载一些损坏的数据,或者是否缺少终止符,这似乎意味着请求被截断。您是否可能没有在某处刷新缓冲区?
Dim dataStream As System.IO.Stream = HttpContext.Current.Request.InputStream
Dim reader As New System.IO.StreamReader(dataStream)

Dim SyncData As New List(Of Procedimentosmidias.Procedimentosmidias)
SyncData = JsonConvert.DeserializeObject(Of List(Of Procedimentosmidias.Procedimentosmidias))(reader.ReadToEnd)

For Each item As Procedimentosmidias.Procedimentosmidias In SyncData
            If Not xString.IsObjectNullOrEmpty(item.ImageBytes) Then
                        Dim caminho As String = Sys.AppClient.ClientAppFiles(item.ClientId.ToString) + "/" + Path.GetFileName(item.PathMidia)
                        EquinovetMobile.ConvertBytesToImageFile(item.ImageBytes, Server.MapPath(caminho))
                        item.PathMidia = ResolveUrl(caminho)
            End If
            Datapost.Mobile.InsertUpdateSync(userToken, tabela, item, "ProcedimentoMidiaId", item.ProcedimentoMidiaId.ToString())
Next


Public Shared Function ConvertBytesToImageFile(ByVal ImageData As Byte(), ByVal FilePath As String) As Boolean
        If Not IsNothing(ImageData) Then
            Dim fs As FileStream = New FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.Write)
            Dim bw As BinaryWriter = New BinaryWriter(fs)
            bw.Write(ImageData)
            bw.Flush()
            bw.Close()
            fs.Close()
            bw = Nothing
            fs.Dispose()
            ConvertBytesToImageFile = True
        Else
            ConvertBytesToImageFile = False
        End If
End Function