客户端:
public static submitTurnResult submitTurn(int turnID,Stream fileStream){ httpClIEnt clIEnt = CreatehttpClIEnt(); httpContent content = new StreamContent(fileStream); content.headers.Contentdisposition = new ContentdispositionheaderValue("attachment"); content.headers.Contentdisposition.filename = "new-turn.Civ5Save"; content.headers.ContentType = new MediaTypeheaderValue("application/octet-stream"); content.headers.ContentLength = fileStream.Length; httpResponseMessage response = clIEnt.PostAsync( string.Format("submitTurn?authKey={0}&turnID={1}",LocalSettings.Instance.AuthenticationKey,turnID ),content ).Result; response.EnsureSuccessstatusCode(); return response.Content.ReadAsAsync<submitTurnResult>().Result;}
submitTurnResult是一个枚举,用于定义服务器上的结果,turnID是此文件附加到的实体的ID,fileStream是读取磁盘字节的实际fileStream.
服务器端:
[httpGet,httpPost]public submitTurnResult submitTurn(string authKey,int turnID){ try { bool worked = false; int gameID = 0; using (GmrEntitIEs gmrDb = new GmrEntitIEs()) { var player = gmrDb.Users.FirstOrDefault(u => u.AuthKey == authKey); if (player != null) { var turn = player.Turns.FirstOrDefault(t => t.TurnID == turnID); if (turn != null) { byte[] savefileBytes = null; using (MemoryStream tempStream = new MemoryStream()) { var task = this.Request.Content.copyToAsync(tempStream); task.Wait(); savefileBytes = tempStream.ToArray(); tempStream.Close(); } if (savefileBytes.Length != this.Request.Content.headers.ContentLength.Value) { throw new Exception(string.Format("Byte array length ({0}) not equal to http content-length header ({1}). This is not good!",savefileBytes.Length,this.Request.Content.headers.ContentLength.Value)); } worked = GameManager.submitTurn(turn,savefileBytes,gmrDb); if (worked) { gameID = turn.Game.GameID; gmrDb.SaveChanges(); } } } } return submitTurnResult.OK; } catch (Exception exc) { DeBUGLogger.WriteExceptionWithComments(exc,string.Format("Diplomacy: Sumbitting turn for turnID: {0}",turnID)); return submitTurnResult.UnexpectedError; }}解决方法 正如我之前的评论中所述,我们遇到了与StreamContent相同的行为,但是在从windows Server 2003 Web API服务流式传输响应时.它不会在2008年重新生成.实际上,如果我使用少量RAM(712 MB)配置VM,它也会在windows Server 2008上进行重新编译,但是如果使用4 GB RAM则不会重新编译.此外,我们发现这只有一个带有fileStream的repros.将fileStream转换为MemoryStream会绕过问题(当然是以内存为代价).我们发现当响应流提前终止时,它总是在4096字节的边界上,并且它达到大约3.5MB的上限.
以下是根据您的代码示例量身定制的解决方法:
public static submitTurnResult submitTurn(int turnID,Stream fileStream){ httpClIEnt clIEnt = CreatehttpClIEnt(); var memoryStream = new MemoryStream((int)fileStream.Length); fileStream.copyTo(memoryStream); fileStream.Close(); memoryStream.Seek(0,SeekOrigin.Begin); httpContent content = new StreamContent(memoryStream);
如果需要,只有在Stream是fileStream时才可以有条件地执行MemoryStream复制.
总结以上是内存溢出为你收集整理的c# – ASP.Net Web API不读取StreamContent中的所有字节全部内容,希望文章能够帮你解决c# – ASP.Net Web API不读取StreamContent中的所有字节所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)