如何使用web api发布和接收文件

时间:2015-12-08 23:58:05

标签: c# asp.net-web-api2

我有一个Api Post方法,我希望能够接受任何文件类型,如下所示:

[HttpPost]
    public async Task<IHttpActionResult> Post()
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        var provider = new MultipartMemoryStreamProvider();
        await Request.Content.ReadAsMultipartAsync(provider);

        if (provider.Contents.Count != 1)
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest,
                "You must include exactly one file per request."));
        }

        var file = provider.Contents[0];
        var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
        var buffer = await file.ReadAsByteArrayAsync();
  }

当我尝试将图像发布到它时,这适用于小提琴手。但是,我正在编写一个客户端库,我有一个看起来像这样的方法:

        public string PostAttachment(byte[] data, Uri endpoint, string contentType)
    {
        var request = (HttpWebRequest)WebRequest.Create(endpoint);
        request.Method = "POST";
        request.ContentType = contentType;
        request.ContentLength = data.Length;

        var stream = request.GetRequestStream();
        stream.Write(data, 0, data.Length);
        stream.Close();

        var response = (HttpWebResponse) request.GetResponse();
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
           return reader.ReadToEnd();
        }            
    }

每当我尝试使用此图片发布图片时,我都会收到UnsuportedMediaType错误。我假设它是因为我的图像不是多部分内容?有没有一种简单的方法来提出正确类型的请求?

如果我必须更改我的web api post方法,是否有一种简单的方法可以在不将文件写入服务器并将其保留在内存中的情况下执行此操作?

1 个答案:

答案 0 :(得分:3)

MultipartFormDataContent命名空间中的System.Net.Http将允许您发布多部分表单数据。

private async Task<string> PostAttachment(byte[] data, Uri url, string contentType)
{
  HttpContent content = new ByteArrayContent(data);

  content.Headers.ContentType = new MediaTypeHeaderValue(contentType); 

  using (var form = new MultipartFormDataContent())
  {
    form.Add(content);

    using(var client = new HttpClient())
    {
      var response = await client.PostAsync(url, form);
      return await response.Content.ReadAsStringAsync();
    }
  }
}