2

I am writing a console application that needs to perform a POST to an MVC controller. I am using the WebClient class to perform the POST. But I'm having trouble understanding how to add arrays to the message body.

For simple parameters, it seems to work if I do this:

         using (var client = new WebClient())
        {

            var values = new NameValueCollection 
            { 
                { "userName", "userName" },
                { "password", "passwordGoesHere"}

            };
            byte[] responseArray = client.UploadValues(String.Format("{0}/Mobile/StartSession", serverAddress), values);
            Debug.WriteLine(String.Format("\r\nResponse received was :\n{0}\n", Encoding.ASCII.GetString(responseArray)));

        }

I was trying to find how to pass arrays in the message body when using WebClient (for calling one of the other methods). I came across this solution: POST'ing arrays in WebClient (C#/.net)

It appears the solution actually passes parameters in the query string (and not in the message body). This seems to work in any case, as the HttpPost method on the MVC controller is still receiving the correct information. However, another method requires that I pass an image as an array of bytes. This is too large to be passed in the querystring and so the call fails.

So my question is, using the code I provided above, how can I add arrays in there as well. So an array of bytes for example, but also an array of strings.

If any one can provide me with a solution it would be much appreciated, or if I'm incorrect in my thinking please let me know.

Thanks

Community
  • 1
  • 1
King_Nothing
  • 480
  • 1
  • 5
  • 15

1 Answers1

1

Instead of using array of bytes maybe you should POST a file in the same way files are uploaded from browser from file inputs. This way you will save some transfered bytes, but you have to use HttpWebRequest instead of WebClient. More about this solution is here:

Upload files with HTTPWebrequest (multipart/form-data)

You upload bytes as "multipart/form-data" content type. On the server you will receive the streams of bytes in Request.Files collection.

Community
  • 1
  • 1
PanJanek
  • 6,593
  • 2
  • 34
  • 41