102

I have some JavaScript code that I need to convert to C#. My JavaScript code POSTs some JSON to a web service that's been created. This JavaScript code works fine and looks like the following:

var vm = { k: "1", a: "2", c: "3", v: "4" };
$.ajax({
  url: "http://www.mysite.com/1.0/service/action",
  type: "POST",
  data: JSON.stringify(vm),
  contentType: "application/json;charset=utf-8",
  success: action_Succeeded,
  error: action_Failed
});

function action_Succeeded(r) {
  console.log(r);
}

function log_Failed(r1, r2, r3) {
  alert("fail");
}

I'm trying to figure out how to convert this to C#. My app is using .NET 2.0. From what I can tell, I need to do something like the following:

using (WebClient client = new WebClient())
{
  string json = "?";
  client.UploadString("http://www.mysite.com/1.0/service/action", json);
}

I'm a little stuck at this point. I'm not sure what json should look like. I'm not sure if I need to set the content type. If I do, I'm not sure how to do that. I also saw UploadData. So, I'm not sure if I'm even using the right method. In a sense, the serialization of my data is my problem.

Can someone tell me what I'm missing here?

Thank you!

Eels Fan
  • 2,043
  • 6
  • 22
  • 23

3 Answers3

218

The question is already answered but I think I've found the solution that is simpler and more relevant to the question title, here it is:

var cli = new WebClient();
cli.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = cli.UploadString("http://some/address", "{some:\"json data\"}");

PS: In the most of .net implementations, but not in all WebClient is IDisposable, so of cource it is better to do 'using' or 'Dispose' on it. However in this particular case it is not really necessary.

sarh
  • 6,371
  • 4
  • 25
  • 29
81

The following example demonstrates how to POST a JSON via WebClient.UploadString Method:

var vm = new { k = "1", a = "2", c = "3", v=  "4" };
using (var client = new WebClient())
{
   var dataString = JsonConvert.SerializeObject(vm);
   client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
   client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}

Prerequisites: Json.NET library

Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193
  • 4
    I think that should be UploadStringAsync if you are using the completed event. – Sam Mackrill Jan 22 '15 at 13:38
  • You could omit the `POST` argument as `UploadString` implicitly uses this method as default. Furthermore you may want to add `client.Headers.Add(HttpRequestHeader.Accept, "application/json");` if you expect `JSON` as return. – jimasun Aug 04 '17 at 08:33
  • Does WebClient actually implement IDisposable? I'm working in .NET Framework 4.7.1 a few years later and I don't see it. – bubbleking Nov 10 '18 at 13:27
  • 2
    @bubbleking I clicked F12 on WebClient and see that it is a Component and Component implements IDisposable `public class WebClient : Component` `public class Component : MarshalByRefObject, IComponent, IDisposable` – Lars Persson Mar 04 '19 at 09:40
76

You need a json serializer to parse your content, probably you already have it, for your initial question on how to make a request, this might be an idea:

var baseAddress = "http://www.example.com/1.0/service/action";

var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";

string parsedContent = <<PUT HERE YOUR JSON PARSED CONTENT>>;
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);

Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();

var response = http.GetResponse();

var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

hope it helps,

Sajad Afaghiy
  • 524
  • 5
  • 12
Jorge Alvarado
  • 2,664
  • 22
  • 33
  • 1
    what should "parsedContent" look like? Unfortunately, I need to manually create my JSON in this scenario. Thank you. – Eels Fan Feb 26 '13 at 14:43
  • Can it just look like JSON? Or do I need to do some kind of special encoding is what I'm getting at. – Eels Fan Feb 26 '13 at 14:43
  • @EelsFan usually is not a problem to choose any JSON parser, you can always JSON.Net to parse a .net object into JSON, but in my experience there were some cloud services that had a different JSON parser version and I had to make some tweaks. Do what is best for your scenario, this discussion might help you too see some issues without JSON.Net http://stackoverflow.com/questions/9573119/how-to-parse-json-without-json-net-library – Jorge Alvarado Feb 26 '13 at 14:58
  • 5
    Why do you use ASCIIEncoding, and not UTF8? See http://stackoverflow.com/a/9254967/109392. – awe Jun 06 '13 at 08:53
  • 2
    +1 I first tried similar to OP using `WebClient`, and did not get it to work. Then I tried this sollution, and it worked like a charm. I was using `UTF8Encoding` instead of `ASCIIEncoding` to create the byte array, because I see no reason to use ASCII, which reduces available characters in a way that is unacceptable. ASCII only has 127 characters in the charset. – awe Jun 06 '13 at 09:11
  • I need t0 send some data to web api service ..where to define To Post data ? – waqari Jan 21 '14 at 06:19
  • and when i call this it returns protocolerror internall error 500 when u get web response..any help would be greatly appreciated – waqari Jan 21 '14 at 06:33
  • thank you , your way is the best solution to send this data to my api: { "applications": ["com.example.app"], "notification": { "title": "MyTitle", "content": "MyContent" } } – hossein andarkhora Feb 13 '18 at 13:07