加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 为什么POST会在MVC 4中引发异常?

发布时间:2020-12-16 03:27:47 所属栏目:asp.Net 来源:网络整理
导读:我想尝试这样的POST: HttpClient hc = new HttpClient(); byte[] bytes = ReadFile(@"my_path"); var postData = new ListKeyValuePairstring,string(); postData.Add(new KeyValuePairstring,string("FileName","001.jpeg")); postData.Add(new KeyValuePa
我想尝试这样的POST:

HttpClient hc = new HttpClient();
    byte[] bytes = ReadFile(@"my_path");

    var postData = new List<KeyValuePair<string,string>>();
    postData.Add(new KeyValuePair<string,string>("FileName","001.jpeg"));
    postData.Add(new KeyValuePair<string,string>("ConvertToExtension",".pdf"));
    postData.Add(new KeyValuePair<string,string>("Content",Convert.ToBase64String(bytes)));

    HttpContent content = new FormUrlEncodedContent(postData);
    hc.PostAsync("url",content).ContinueWith((postTask) => {
    postTask.Result.EnsureSuccessStatusCode();
    });

但我收到这个例外:

Invalid URI: The Uri string is too long.

抱怨这一行:HttpContent content = new FormUrlEncodedContent(postData);.对于小文件它可以工作,但我不明白为什么对于较大的文件它不?

当我发布POST时,内容可能会更大……那么为什么它会抱怨URI?

解决方法

您应该使用MultipartFormDataContent( http://msdn.microsoft.com/en-us/library/system.net.http.multipartformdatacontent%28v=vs.110%29)而不是FormUrlEncodedContent,它将您的数据发送为“application / x-www-form-urlencoded”.

因此,即使您使用POST动词,它仍然会发送到包含您的数据的非常长的URL,因此错误.

The content type “application/x-www-form-urlencoded” is inefficient
for sending large quantities of binary data or text containing
non-ASCII characters. The content type “multipart/form-data” should be
used for submitting forms that contain files,non-ASCII data,and
binary data.

见:http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1

有关示例,请查看此答案:ASP.NET WebApi: how to perform a multipart post with file upload using WebApi HttpClient

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读