HttpClient Multipart Form Post in C#

前端 未结 4 2134
既然无缘
既然无缘 2020-12-12 22:24

I\'m trying to do a multipart form post using the HttpClient in C# and am finding the following code does not work.

Important:

var j         


        
4条回答
  •  悲哀的现实
    2020-12-12 22:41

    public class CourierMessage
    {
        public string Id { get; set; }
        public string Key { get; set; }
        public string From { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
        public DateTimeOffset Processed { get; set; }
        public DateTime Received { get; set; }
        public DateTime Created { get; set; }
        public DateTime Sent { get; set; }
        public HttpPostedFileBase File { get; set; }
    }  
    
    
    
    
    while (true)
    {
        Console.WriteLine("Hit any key to make request.");
        Console.ReadKey();
    
        using (var client = new HttpClient())
        {
            using (var multipartFormDataContent = new MultipartFormDataContent())
            {
                var values = new[]
                {
                    new KeyValuePair("Id", Guid.NewGuid().ToString()),
                    new KeyValuePair("Key", "awesome"),
                    new KeyValuePair("From", "khalid@home.com")
                     //other values
                };
    
                foreach (var keyValuePair in values)
                {
                    multipartFormDataContent.Add(new StringContent(keyValuePair.Value), 
                        String.Format("\"{0}\"", keyValuePair.Key));
                }
    
                multipartFormDataContent.Add(new ByteArrayContent(File.ReadAllBytes("test.txt")), 
                    '"' + "File" + '"', 
                    '"' + "test.txt" + '"');
    
                var requestUri = "http://localhost:5949";
                var result = client.PostAsync(requestUri, multipartFormDataContent).Result;
            }
        }
    }  
    

    enter image description here

提交回复
热议问题