2

我正在尝试调用 Web api 方法来保存文件数据。当我调试 Webapi 方法时,我发现 ContentLength 不正确,因为当我检索文件时它显示错误为损坏的文件。

我的班级方法是:-

  using (var formData = new MultipartFormDataContent())
   {
     HttpContent stringContent = new StringContent(file);
      formData.Add(stringContent, "file", file);
      formData.Add(new StringContent(JsonConvert.SerializeObject(file.Length)), "ContentLength ");
      HttpResponseMessage responseFile = client.PostAsync("Report/SaveFile?docId=" + docId, formData).Result;
  }

我的 Web api 方法是:-

 [HttpPost]
        public HttpResponseMessage SaveFile(long docId)
        {
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Unauthorized);
            try
            {
                var httpRequest = HttpContext.Current.Request;
                bool IsSuccess = true;
                if (httpRequest.Files.Count > 0)
                {
                    var docfiles = new List<string>();
                    foreach (string file in httpRequest.Files)
                    {
                        HttpPostedFile postedFile = httpRequest.Files[file];
                        // Initialize the stream.
                        Stream myStream = postedFile.InputStream;
                        myStream.Position = 0;
                        myStream.Seek(0, SeekOrigin.Begin);
                        var _item = CorrectedReportLibrary.Services.ReportService.SaveFile(myStream,docId);
                        response = Request.CreateResponse<bool>((IsSuccess)
                                                                      ? HttpStatusCode.OK
                                                                      : HttpStatusCode.NoContent,
                                                                  IsSuccess);
                    }
                }
            }
            catch (Exception ex)
            {
                Theranos.Common.Library.Util.LogManager.AddLog(ex, "Error in CorrectedReportAPI.Controllers.SaveDocument()", null);
                return Request.CreateResponse<ReportDocumentResult>(HttpStatusCode.InternalServerError, null);

            }
            return response;
        }

如何设置ContentLengthfrom C# 类方法?

4

2 回答 2

0

ContentLength将其用作类的第二个参数看起来有点奇怪StringContent。假设是您要使用的编码,例如 new StringContent(content, Encoding.UTF8). 我认为这里的问题不是内容长度。

字符串内容类

我猜因为它是您要上传的文件,所以您已经将该文件作为流读取,所以我通常会这样做:

客户:

private async Task UploadFile(MemoryStream file)
{
    var client = new HttpClient();
    var content = new MultipartFormDataContent();
    content.Add(new StreamContent(file));
    var result = await client.PostAsync("Report/SaveFile?docId=" + docId, content);
}

编辑。由于它是多部分形式,因此让框架处理细节更容易。尝试这样的事情:

服务器:

[HttpPost]
public async Task<HttpResponseMessage> SaveFile(long docId)
{
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Unauthorized);
    try
    {
        var filedata = await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider());
        foreach(var file in filedata.Contents)
        {
            var fileStream = await file.ReadAsStreamAsync();
        }

        response = Request.CreateResponse<bool>(HttpStatusCode.OK, true);
    }
    catch (Exception ex)
    {
        response = Request.CreateResponse<bool>(HttpStatusCode.InternalServerError, false);
    }
    return response;
}
于 2016-12-05T09:11:54.193 回答
0

最后我发现解决方案不需要更改web api服务,问题来自我直接传递文件数据的客户端,现在修改后的工作代码是这样的: -

 using (var formData = new MultipartFormDataContent())
 {
    var bytes = File.ReadAllBytes(file);
     formData.Add(new StreamContent(new MemoryStream(bytes)), "file", file);
     HttpResponseMessage responseFile = client.PostAsync("ReportInfo/SaveFile?docId=" + docId, formData).Result;
 }
于 2016-12-05T11:11:04.107 回答