5

Client:

WebClient wc = new WebClient();
try
{
    string json = wc.UploadString("http://localhost:50001/Client/Index", "1");
    dynamic receivedData = JsonConvert.DeserializeObject(json);
    Console.WriteLine("Result: {0};",receivedData.data);
}
catch (Exception e)
{
    Console.WriteLine("Oh bother");
    Console.WriteLine();
    Console.WriteLine(e.Message);
}

Basically sends "1" to the Index action in the Client controller.

Here is the Controller:

[HttpPost]
public ActionResult Index(string k)
{
  Debug.WriteLine(String.Format("Result: {0};", k));
  return Json(new { data = k}, JsonRequestBehavior.DenyGet);
}

The result from the Client is just "Result: ;". The debug output from the controller is also "Result: ;". This means that the data is lost somewhere between the client and the site. But when I debug, Visual Studio says that there was one request.

3
  • stackoverflow.com/questions/5401501/… --Possible Duplicate Commented Apr 7, 2017 at 11:11
  • @TKHN Do you think it is because I use UploadString but not UploadData and it should be a byte array? Commented Apr 7, 2017 at 11:23
  • @TKHN I tried byte[] but the NullException kiks in. Commented Apr 7, 2017 at 11:31

4 Answers 4

2

By adding the header and specifying the parameter name, I've managed to get this to work (in your calling method):

 static void Main(string[] args)
        {
            WebClient wc = new WebClient();
            try
            {
                wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                string json = wc.UploadString("http://localhost:49847/Home/Index", "k=1");
                dynamic receivedData = JsonConvert.DeserializeObject(json);
                Console.WriteLine("Result: {0};", receivedData.data);
            }
            catch (Exception e)
            {
                Console.WriteLine("Oh bother");
                Console.WriteLine();
                Console.WriteLine(e.Message);
            }
        }

From MSDN:

...set the HTTP Content-Type header to application/x-www-form-urlencoded, to notify the server that form data is attached to the post.

I haven't run fiddler to check what (if any) headers are sent through by default but I suspect the reason this doesn't work without the header is the receiving client doesn't know where to find the query string parameters passed through.

From another answer on StackOverflow:

When receiving a POST request, you should always expect a "payload", or, in HTTP terms: a message body. The message body in itself is pretty useless, as there is no standard (as far as I can tell. Maybe application/octet-stream?) format. The body format is defined by the Content-Type header. When using a HTML FORM element with method="POST", this is usually application/x-www-form-urlencoded.

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

1 Comment

Works fine. Thanks a lot!
2

WebAPI may be interpreting your argument as a URI argument.

Try this:

[HttpPost]
public ActionResult Index([FromBody] string k)
{
    Debug.WriteLine(String.Format("Result: {0};", k));
    return Json(new { data = k}, JsonRequestBehavior.DenyGet);
}

This tells WebAPI to expect this argument to be lifted from the body of the request (e.g. a JSON post payload)

1 Comment

Doesn't work. Yet this is with [System.Web.Mvc.HttpPost]
2

Try

            string parameters = string.Concat("k=","1");

            string url = "http://localhost:50001/Client/Index";
            using (Var wc = new WebClient()){

            wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded;charset=UTF-8";

            string result = wc.UploadString(url, parameters);

            JObject obj = JObject.Parse(result);

            Console.WriteLine("Result: {0};", obj.data);               

            }`

1 Comment

` string parameters = string.Concat("k=","1"); string url = "localhost:50001/Client/Index"; using (Var wc = new WebClient()){ wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded;charset=UTF-8"; string result = wc.UploadString(url, parameters); JObject obj = JObject.Parse(result); Console.WriteLine("Result: {0};", obj.data); } `
1

You need to slightly change your action to fetch posted value from Request stream:

[HttpPost]
public ActionResult Index(string k)
{      
    var stream = Request.InputStream;
    string value = string.Empty;

    using (var reader = new StreamReader(stream))
    {
        value = reader.ReadToEnd();
    }

    Debug.WriteLine(String.Format("Result: {0};", value));
    return Json(new { data =  value}, JsonRequestBehavior.DenyGet);
}

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.