我在我的网站上设置了一个 ASP.Net Web API,用于与 WPF 桌面应用程序进行通信。我在 API 上有一个操作设置,用于从客户端应用程序接收二进制文件。但是,在某些(看似随机的)情况下,当我从请求中获取所有字节时,并非所有字节都被读取。希望你能给我一个想法,告诉我如何以一种始终有效的方式做到这一点。这是代码:
客户端:
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;
}
}