C#.NET 4.0上传文件为.asp的Web API [英] C# .net 4.0 Upload a file to .asp Web API

查看:1424
本文介绍了C#.NET 4.0上传文件为.asp的Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的.NET 4.0类库发送的Htt prequestMessage和接收的Htt presponseMessage从.asp的网络API(REST)。

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

当我发了小班,我使用JSON解析它的字符串,然后我送字符串方式:

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

接下来,使用的HttpClient来发送:

Next, use HttpClient to send it:

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

本作品
现在,我的课得到了更大的,我怎么能送吗?
我所做的就是要压缩并发送作为ByteArrayContent。

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

和发送相同的方式。

不过现在的服务器执行,错误回答我:

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'.

我在做什么错了?我想找到一个合适的引导,所有的导游都在谈论上传发件人网络API,而不是有关从应用程序网络API上传。

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..

推荐答案

去拿WebAPIContrib,它有一个<一个href="https://github.com/WebApiContrib/WebAPIContrib/blob/master/src/WebApiContrib/Content/Com$p$pssedContent.cs"相对=nofollow>的COM pressedContent 类

Go get WebAPIContrib, it has a CompressedContent class

有了它,你可以做的,

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

和COM pression会神奇地只是发生。

and compression will just magically just happen.

这篇关于C#.NET 4.0上传文件为.asp的Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆