【问题标题】:How to pass the File Data from C# Console application to WebApi?如何将文件数据从 C# 控制台应用程序传递到 WebApi?
【发布时间】:2017-04-19 12:56:18
【问题描述】:

我正在尝试调用 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;
        }

如何从 C# 类方法中设置ContentLength

【问题讨论】:

    标签: c# asp.net-web-api http-post console-application httpcontent


    【解决方案1】:

    您使用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;
    }
    

    【讨论】:

    • 下面的代码我按照你说的添加了,但同样的问题是 ids 文件已损坏:contents.Add(new StreamContent(stre),"file",file); var result = await client.PostAsync("ReportInfo/SaveFile?docId=" + docId, contents);
    • @gorakh 更新了服务器端示例
    【解决方案2】:

    最后我找到了不需要更改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;
     }
    

    【讨论】:

      猜你喜欢
      • 2018-12-05
      • 2021-04-06
      • 2014-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多