2
using (WebClient wc = new WebClient())
{
    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    string HtmlResult = wc.UploadString(url, "sign=fsadfasdf&charset=utf-8");
}

Server can get value of sign and charset.

But there is a third parameter LIST, which is a list of object (this object is an entity class). How can I pass this parameter to the server?

I tried to use "sign=fsadfasdf&charset=hhh&list=" + Json(list) as postData (convert List to json string). But the server didn't get value of this list param.

wtf512
  • 4,487
  • 9
  • 33
  • 55
  • That depends on how the server *interprets* the list. Can you give more info? The is no "default way" to handle lists. – Willem Van Onsem Jan 20 '15 at 10:23
  • possible duplicate of [POST'ing arrays in WebClient (C#/.net)](http://stackoverflow.com/questions/3942427/posting-arrays-in-webclient-c-net) – Uriil Jan 20 '15 at 10:24
  • Try `UploadValues()` instead - http://msdn.microsoft.com/en-us/library/9w7b4fz7(v=vs.110).aspx – Kami Jan 20 '15 at 10:25

1 Answers1

4

I hate to post 1 line answers with links in them but this has been solved on here before ...

POSTing JsonObject With HttpClient From Web API

HttpClient class is designed to solve exactly this problem, i believe its found in the nuget package "Microsoft.AspNet.WebApi.Client", this should add the namespace "System.Net.Http" to your project.

It's also geared at being completely async which should be nicer to your server!

EDIT: To post an array / collection you would do something like this ...

var myObject = (dynamic)new JsonObject();
myObject.List = new List<T>();
// add items to your list

httpClient.Post(
    "",
    new StringContent(
        myObject.ToString(),
        Encoding.UTF8,
        "application/json"));
Community
  • 1
  • 1
War
  • 8,539
  • 4
  • 46
  • 98
  • So easy! Thanks ! (Comments must be at least 15 characters in length.) – wtf512 Jan 20 '15 at 10:55
  • Most of my problems these days come down to using the wrong tool for the job ... HttpClient is perfect for this async json posting stuff, webclient has a known problem in this area ... in short ... glad I could help :) – War Jan 20 '15 at 11:07