2012-08-15 12 views
5

私はこのようなPOSTをやろうとしています:なぜPOSTはMVC 4で例外をスローしますか?

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

が、私はこの例外を受け取る:

無効なURI:URI文字列が長すぎます。

この行について不平を言う:HttpContent content = new FormUrlEncodedContent(postData);。小さなファイルの場合は動作しますが、大きなファイルの場合はそうではありません。

POSTを実行すると、コンテンツが大きくなる可能性があります。なぜURIについて不平を言うのですか?

答えて

4

FormUrlEncodedContentの代わりにMultipartFormDataContent(http://msdn.microsoft.com/en-us/library/system.net.http.multipartformdatacontent%28v=vs.110%29)を使用する必要があります。これは、データを "application/x-www-form-urlencoded"として送信します。

POST動詞を使用していても、あなたのデータを含んでいる非常に長いURLにPOSTingしているので、エラーです。

コンテンツタイプ "アプリケーション/ x-www-form-urlencodedでは" 非ASCII文字を含むバイナリデータまたはテキストを大量に送信するため 非効率的です。コンテンツタイプ「multipart/form-data」は、ファイル、ASCII以外のデータ、および のバイナリデータを含むフォームの送信には である必要があります。

参照:サンプルについて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

+0

ありがとうございます!これを行う方法の例はありますか?これは正しいです? 'MultipartFormDataContent multipartFormDataContent =新しいMultipartFormDataContent(); multipartFormDataContent.Add(新しいFormUrlEncodedContent(postData)); ' –

+0

@CristianBoariu FormUrlEncodedContentがビルドされているので、サンプルが – mathieu

+1

@mathieu @ Exceptionをスローするサンプルをリンクするための私の答えを更新しました。 –

0

私は、これはすでに回答されている知っているが、私はこの同じ問題に遭遇し、それがされているましたFormUrlEncodedContentクラスの制限。エラーの理由は、オブジェクトのエンコーディングがUri.EscapeDataString()によって処理されているためです。 This post explains it on CodePlex.代わりに、HTTPUtilityクラスを使用して、URLエンコードの独自の解決策を思いつきました。

using System.Collections.Generic; 
using System.Linq; 
using System.Net.Http; 
using System.Text; 
using System.Web; 

namespace Wfm.Net.Http 
{ 
    public class UrlContent : ByteArrayContent 
    { 
     public UrlContent(IEnumerable<KeyValuePair<string, string>> content) 
      : base(GetCollectionBytes(content, Encoding.UTF8)) 
     { 
     } 

     public UrlContent(byte[] content, int offset, int count) : base(content, offset, count) 
     { 
     } 

     private static byte[] GetCollectionBytes(IEnumerable<KeyValuePair<string, string>> c, Encoding encoding) 
     { 
      string str = string.Join("&", c.Select(i => string.Concat(HttpUtility.UrlEncode(i.Key), '=', HttpUtility.UrlEncode(i.Value))).ToArray()); 
      return encoding.GetBytes(str); 
     } 
    } 


} 

私はそれをどのように実装したかを小文字で書きました。これは誰もが同じ問題を抱えていることを願っています。

関連する問題