0

I want to send via POST request two parameters to a Web API service. I am currently receiving 404 not found when I try in the following way, as from msdn:

public static void PostString (string address)
{
    string data = "param1 = 5 param2 = " + json;
    string method = "POST";
    WebClient client = new WebClient ();
    string reply = client.UploadString (address, method, data);

    Console.WriteLine (reply);
}

where json is a json representation of an object. This did not worked, I have tried with query parameters as in this post but the same 404 not found was returned.

Can somebody provide me an example of WebClient which sends two parameters to a POST request?

Note: I am trying to avoid wrapping both parameters in the same class only to send to the service (as I found the suggestion here)

4
  • It looks like you're trying to combine url encoded parameters with a stringified json object. That won't work. Commented Aug 1, 2016 at 12:43
  • @mituw16 yes, I tried to combine a url encoded parameter with a stringified json, and that did not worked, but how can I achieve this? Commented Aug 1, 2016 at 12:45
  • You need to either have all stringified JSON or have all url encoded parameters. Commented Aug 1, 2016 at 12:51
  • @meJustAndrew, Show target Web api end point. Commented Aug 1, 2016 at 17:26

2 Answers 2

0

I would suggest sending your parameters as a NameValueCollection.

Your code would look something like this when sending the parameters with a NameValueCollection:

using(WebClient client = new WebClient())
        {
            NameValueCollection requestParameters = new NameValueCollection();
            requestParameters.Add("param1", "5");
            requestParameters.Add("param2", json);
            byte[] response = client.UploadValues("your url here", requestParameters);
            string responseBody = Encoding.UTF8.GetString(response);
        }

Using UploadValues will make it easier for you, since the framework will construct the body of the request and you won't have to worry about concatenating parameters or escaping characters.

Sign up to request clarification or add additional context in comments.

Comments

0

I have managed to send both a json object and a simple value parameter by sending the simple parameter in the address link and the json as body data:

public static void PostString (string address)
{
    string method = "POST";
    WebClient client = new WebClient ();
    string reply = client.UploadString (address + param1, method, json);

    Console.WriteLine (reply);
}

Where address needs to expect the value parameter.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.