1

我試圖調用Web api方法來保存文件數據。當我調試Webapi方法時,我發現ContentLength不是正確的,因爲當我檢索文件時,它顯示錯誤爲損壞的文件。如何將文件數據從C#控制檯應用程序傳遞給WebApi?

我的班級的方法是: -

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; 
     } 

如何設置從C#類方法的ContentLength

回答

0

看起來有點奇怪,您使用ContentLength作爲StringContent類的第二個參數。假設您想使用哪種編碼,例如 new StringContent(content, Encoding.UTF8)。我認爲這不是問題的內容長度。

StringContent class

我既然猜到是你要上傳的文件,你已經讀作流的文件,所以我通常做這樣的事情:

客戶:

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; 
} 
+0

下面的代碼我加你告知,但還是同樣的問題出現以後,IDS文件已損壞ed:contents.Add(new StreamContent(stre),「file」,file); var result = await client.PostAsync(「ReportInfo/SaveFile?docId =」+ docId,contents); – jack123

+0

@gorakh更新服務器端示例 – Hypnobrew

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; 
} 
相關問題