我有一些我需要转换为C#的JavaScript代码。我的JavaScript代码将一些JSON发布到已创建的Web服务。此JavaScript代码工作正常,如下所示:
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");
}
我正在试图弄清楚如何将其转换为C#。我的应用程序使用的是.NET 2.0。据我所知,我需要做以下事情:
using (WebClient client = new WebClient())
{
string json = "?";
client.UploadString("http://www.mysite.com/1.0/service/action", json);
}
我现在有点卡住了。我不确定json
应该是什么样的。我不确定是否需要设置内容类型。如果我这样做,我不知道该怎么做。我也看到了UploadData
。所以,我不确定我是否使用了正确的方法。从某种意义上说,我的数据序列化是我的问题。
有人能告诉我我在这里缺少什么吗?
谢谢!
答案 0 :(得分:168)
这个问题已经得到解答,但我认为我已经找到了一个更简单且更符合问题标题的解决方案,这里是:
var cli = new WebClient();
cli.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = cli.UploadString("http://some/address", "{some:\"json data\"}");
答案 1 :(得分:63)
您需要一个json序列化程序来解析您的内容,可能您已经拥有它, 关于如何提出请求的初步问题,这可能是一个想法:
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();
希望它有所帮助,
答案 2 :(得分:60)
以下示例演示了如何通过WebClient.UploadString Method发布JSON:
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);
}
先决条件:Json.NET library