Why does POST throw an exception in MVC 4?

I am trying to do a POST as follows:

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

but I get this exception:

Invalid URI: Uri string is too long.

complaining about this line: HttpContent content = new FormUrlEncodedContent(postData);. For small files, this works, but I don’t understand why for larger files not?

When I do a POST, there may be more content ... Then why is it complaining about a URI?

+5
source share
2 answers

You should use MultipartFormDataContent ( http://msdn.microsoft.com/en-us/library/system.net.http.multipartformdatacontent%28v=vs.110%29 ) instead of FormUrlEncodedContent, which sends your data as "application / x- www-form- urlencoded ".

, POST, POSTING URL-, , , .

"application/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: WebApi HttpClient

+4

, , , FormUrlEncodedContent. , Uri.EscapeDataString(). CodePlex. Url Encode, HTTPUtility.

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


}

, . , , .

0

All Articles