【问题标题】:C# .net 4.0 Upload a file to .asp Web APIC# .net 4.0 上传文件到 .asp Web API
【发布时间】:2013-09-15 14:12:51
【问题描述】:

我的 .net 4.0 类库发送 HttpRequestMessage 并从 .asp Web API (REST) 接收 HttpResponseMessage。

我发送一个小类的时候,我用JSON解析成字符串,然后我发送字符串的方式:

request = new HttpRequestMessage();
request.RequestUri = new Uri(myRestAPI);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Method = method;
if (method != HttpMethod.Get)
   request.Content = new StringContent(content, Encoding.UTF8, mthv);

接下来使用HttpClient发送:

using (HttpResponseMessage httpResponse = _client.SendAsync(request).Result)
{..}

这工作很好
现在,我的班级变大了,我该如何发送?
我所做的是将其压缩并作为 ByteArrayContent 发送。

request = new HttpRequestMessage();
request.RequestUri = new Uri(url);
request.Method = method;
if (method != HttpMethod.Get)
   request.Content = new ByteArrayContent(content);
   request.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");

并以同样的方式发送。

但是现在服务器确实给我回复了错误:

No MediaTypeFormatter is available to read an object of type 'Byte[]' from content with media type 'multipart/form-data'.

我做错了什么??我正在尝试找到一个合适的指南,所有指南都在谈论上传 FROM web api,而不是从 application 上传到 web api..

【问题讨论】:

  • ByteArrayContent 发送媒体类型application/octet-stream。如果您真的想发送多部分表单数据,那么您将使用 MultiPartFormDataContent 类。无论哪种方式,您都不应该仅仅因为您想要压缩而更改内容类型。这就是为什么有一个单独的内容编码头。

标签: c# rest .net-4.0 asp.net-web-api


【解决方案1】:

去获取WebAPIContrib,它有一个CompressedContent

有了它你就可以做到,

request.Content = new CompressedContent(new StringContent(content, Encoding.UTF8, mthv),"gzip");

压缩会神奇地发生。

【讨论】:

  • 嗨,这对 .net 4.0 有效吗?当我在控制器上收到它时,我会像以前一样做吗? - 在我刚刚将对象作为输入参数之前 (..[FromBody] mySerializedClass..)
  • @ilansch 该类在 .net 4 中运行良好。至于在服务器上解压缩。我认为 IIS 会自动执行此操作,但是,如果您在自己的主机上,您可能需要 MessageHandler。
  • @ilansch GZipStream 类可以解压缩也可以压缩。这里有一个例子说明如何做到这一点github.com/WebApiContrib/WebAPIContrib/blob/master/src/…
  • 我正在尝试您所说的,我在控制器中收到 null:[HttpPut] public HttpResponseMessage UpdateStatus([FromBody]MyClass systemBase, [FromUri]string systemId, [FromUri]string af = "") {
猜你喜欢
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 2020-07-08
  • 1970-01-01
  • 2013-11-11
  • 1970-01-01
相关资源
最近更新 更多