C# .net 4.0 Upload a file to .asp Web API

2019-08-20 14:44发布

问题:

My .net 4.0 class library send HttpRequestMessage and receive HttpResponseMessage from .asp Web API (REST).

When I sent a small class, I use JSON to parse it as string, then I send string by:

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

Next, use HttpClient to send it:

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

This works fine.
Now, my class has got bigger, How can i send it ?
What i did was to zip it and send as 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");

And send it the same way.

But now the server does reply me with error:

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

What am I doing wrong ?? I am trying to find a proper guide and all the guides are talking about uploading FROM web api and not about uploading from application to web api..

回答1:

Go get WebAPIContrib, it has a CompressedContent class

With it you can do,

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

and compression will just magically just happen.