【发布时间】: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